package com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.economicLossPE.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.dict.service.DictItemService;
import com.css.fxfzfxqh.base.dict.viewobjects.DictEntityVo;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.common.utils.CheckObjFields;
import com.css.fxfzfxqh.common.utils.UpdateUtil;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.modules.buildingIndividual.entity.BuildingIndividualEntity;
import com.css.fxfzfxqh.modules.buildingIndividual.service.BuildingIndividualService;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.service.FxqhBuildingGridDataVersionService;
import com.css.fxfzfxqh.modules.buildingResetUnitPrice.entity.BuildingResetUnitPriceEntity;
import com.css.fxfzfxqh.modules.buildingResetUnitPrice.repository.BuildingResetUnitPriceRepository;
import com.css.fxfzfxqh.modules.buildings.VO.CurveVo;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.CalculationTasks;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.FxqhBuildingPriceTaskEntity;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.FxqhHosPeoTaskEntity;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.YSXMainTable;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.repository.CalculationTasksRepository;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.service.CalculationTasksService;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.BuildingVulnerability;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.PCC;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.Statistics;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.vo.Grid13VO;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.entity.EconomicLosses;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.entity.VillageTownHosPeoEntity;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.repository.EconomicLossEDRepository;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.service.VillageTownHostPeoService;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.entity.PCCName;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.param.AssessParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.YSXUtil;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.casualtiesPE.entity.CasualtiesPECalculation;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.economicLossPE.entity.EconomicLossPD;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.economicLossPE.entity.EconomicLossPDCalculation;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.economicLossPE.param.EconomicLossPECalculationParam;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.economicLossPE.repository.EconomicLossPDRepository;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.economicLossPE.service.EconomicLossPDService;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.economicLossPE.vo.EconomicLossPCCPEVO;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.entity.PsHazardDataValue;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.service.PublicOperateService;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.vo.BasicLibraryVo;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.entity.ResistEarthquakesPECalculation;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.service.ResistEarthquakesPEService;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.model.entity.FxqhAssessPdQhResult;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.repository.EnterAssessQhRepository;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.vo.GdpVO;
import com.css.fxfzfxqh.modules.util.hypergraph.service.HypergraphService;
import com.css.fxfzfxqh.modules.util.repository.PccRepository;
import com.css.fxfzfxqh.modules.util.repository.YSXRepository;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/06/16
 * @Description: 概率评估_经济损失Service
 */
@Service
public class EconomicLossPDServiceImpl implements EconomicLossPDService {
    @Resource
    private EconomicLossPDRepository economicLossPDRepository;
    @Resource
    private SysAreaService sysAreaService;
    @Resource
    SUserService sUserService;
    @Resource
    PccRepository pccRepository;
    @Resource
    EconomicLossEDRepository economicLossEDRepository;
    @Resource
    ResistEarthquakesPEService resistEarthquakesPEService;
    @Resource
    DictItemService dictItemService;
    @Resource
    PublicOperateService publicOperateService;
    @Resource
    JcsjRestManager jcsjRestManager;
    @Resource
    YSXUtil ysxUtil;
    @Resource
    BuildingResetUnitPriceRepository buildingResetUnitPriceRepository;
    @Resource
    VillageTownHostPeoService villageTownHostPeoService;
    @Resource
    FxqhBuildingGridDataVersionService fxqhBuildingGridDataVersionService;
    @Resource
    BuildingIndividualService buildingIndividualService;
    @Resource
    HypergraphService hypergraphService;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    CalculationTasksService calculationTasksService;
    @Resource
    CalculationTasksRepository calculationTasksRepository;
    @Resource
    private YSXRepository ysxRepository;
    //本地缓存
    public static Map<String,JSONArray> disrictMap = new HashMap<>();
    @Resource
    private EnterAssessQhRepository enterAssessQhRepository;

    //新增评估记录
    @Override
    public void addAssess(EconomicLossPD param) {
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        param.setId(UUIDGenerator.getUUID());
        param.setCreateUser(sUser.getCreateUser());
        param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        param.setDelFlag(YNEnum.N.toString());
        //创建人单位
        param.setCompany(sUser.getOrgName());
        //写入省市县
        setCCP(param);
        economicLossPDRepository.addAssess(param);
    }

    //写入省市县
    private void setCCP(EconomicLossPD param) {
        List<PCC> pccList1 = new ArrayList<>();
        List<PCC> pccList = param.getList();
        if (pccList.size() != 0) {
            for (PCC pcc : pccList) {
                if (PlatformObjectUtils.isNotEmpty(pcc.getPpName())) {
                    if (PlatformObjectUtils.isEmpty(pcc.getCityName())) {
                        String childArea1 = sysAreaService.getChildAreaById(pcc.getPid());
                        List<PCCName> objects1 = JSON.parseArray(childArea1, PCCName.class);
                        for (PCCName pccName1 : objects1) {
                            String childArea2 = sysAreaService.getChildAreaById(pccName1.getId());
                            List<PCCName> objects2 = JSON.parseArray(childArea2, PCCName.class);
                            for (PCCName pccName2 : objects2) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pccName1.getId());
                                pcc1.setCityName(pccName1.getName());
                                pcc1.setName(pccName2.getName());
                                pcc1.setId(pccName2.getId());
                                pccList1.add(pcc1);
                            }
                        }
                    } else {
                        if (PlatformObjectUtils.isEmpty(pcc.getName())) {
                            String childArea = sysAreaService.getChildAreaById(pcc.getCid());
                            List<PCCName> objects = JSON.parseArray(childArea, PCCName.class);
                            for (PCCName pccName : objects) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pcc.getCid());
                                pcc1.setCityName(pcc.getCityName());
                                pcc1.setName(pccName.getName());
                                pcc1.setId(pccName.getId());
                                pccList1.add(pcc1);
                            }
                        } else {
                            pcc.setAssessId(param.getId());
                            pcc.setUuid(UUIDGenerator.getUUID());
                            pccList1.add(pcc);
                        }
                    }
                } else {
                    pcc.setAssessId(param.getId());
                    pcc.setUuid(UUIDGenerator.getUUID());
                    pccList1.add(pcc);
                }
            }
            pccRepository.batchSavePCC(pccList1);
        }
    }

    //隔绝id查询
    @Override
    public EconomicLossPD findById(String id) {
        EconomicLossPD byId = economicLossPDRepository.findById(id);
        List<PCC> list = pccRepository.queryToponym(byId.getId());
        byId.setList(list);
        return byId;
    }

    //修改评估记录
    @Override
    public void upDateAssess(EconomicLossPD param) {
        param.setUpdateUser(PlatformSessionContext.getUserID());
        param.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        economicLossPDRepository.upDateAssess(param);
    }

    //获取评估记录code
    @Override
    public String getCode(EconomicLossPD param) {
        //抗震能力确定评估
        StringBuilder code = new StringBuilder("JZW-JJ-GL");
        if (param.getHouseDataFlag().equals("0")) {
            //单体
            code.append("-DT");
        } else if (param.getHouseDataFlag().equals("1")) {
            //网格
            code.append("-WG");
        }
        if (StringUtils.isEmpty(param.getCoordinateRange())) {
            //如果经纬度范围为空
            code.append("-QH");
        } else {
            code.append("-QD");
        }
        if (param.getSeismicInputMode().equals("0")) {
            //烈度
            code.append("-LD");
        } else if (param.getSeismicInputMode().equals("1")) {
            //概率水准
            code.append("-GL");
        } else if (param.getSeismicInputMode().equals("2")) {
            //地震影响场
            code.append("-YX");
        }
        String[] split1 = code.toString().split("-");
        if (split1.length != 6) {
            return code.toString();
        }
        //查询最近一次code
        String oldCode = economicLossPDRepository.queryLatest(code);
        if (StringUtils.isEmpty(oldCode)) {
            code.append("-0001");
        } else {
            String[] split = oldCode.split("-");
            code.append("-").append(getNext(split[6]));
        }
        return code.toString();
    }

    /****
     * 从哪里开始计数 比如startValue=2，则会从003,004,005等
     * @param startValue
     * @return
     */
    public String getNext(String startValue) {
        Integer i = Integer.valueOf(startValue);
        String format = String.format("%04d", i + 1);
        return format;
    }

    //分页
    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, AssessParam param) {
        Map<String, Object> page = economicLossPDRepository.getPage(curPage, pageSize, param);
        List<EconomicLossPD> list = (List<EconomicLossPD>) page.get("rows");
        for (EconomicLossPD obj : list) {
            List<PCC> pccs = pccRepository.queryToponym(obj.getId());
            obj.setList(pccs);
        }
        page.put("rows", list);
        return page;
    }
    //计算值
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calculation(Map<String, Object> param) throws Exception {
        long startTime = System.currentTimeMillis();
        String assessId = (String) param.get("taskId");

        //删除上一次数据
        economicLossPDRepository.deleteCalculation(assessId);
        String userId = PlatformSessionUtils.getUserId();
        // 获取当前区县下的所有建筑物；
        CalculationTasks calculationTasks = calculationTasksService.findById(assessId);
        //默认的经济模型
        EconomicLosses defaultModel = economicLossEDRepository.getDefaultModel();

        //人口与建筑物数据
        List<VillageTownHosPeoEntity> list1 = new ArrayList<>();
        //建筑物结构重置单价
        List<BuildingResetUnitPriceEntity> list2 = new ArrayList<>();

        //如果为网格数据
        if ("1".equals(calculationTasks.getHouseDataFlag())) {
            //查询版本信息获取dataType
            List<DictEntityVo> structureList = dictItemService.getDictItemByDictCode("jzwglgwlx");
//            if ("0".equals(calculationTasks.getRadio2())) {
                //获取评估区域的省市县
                List<PCC> list = calculationTasks.getList();
                if (PlatformObjectUtils.isNotEmpty(list)) {
                    //获取所有省市县的易损性数据
                    for (PCC pcc : list) {
                        Map<String, Map<String, String[]>> mapMap = centerEvaluate1(pcc, structureList,
                                calculationTasks, defaultModel, param, list1, list2);
                        if (mapMap != null && mapMap.size() > 0) {
                            param.put("userId", userId);
                            //List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
                            getInitResultData1(mapMap, defaultModel, calculationTasks, pcc, param,
                                    new ArrayList<>());
                        }
                    }
                }
//            } else if ("1".equals(calculationTasks.getRadio2())) {
//                //圈选评估区域
//                if (PlatformObjectUtils.isNotEmpty(calculationTasks.getCoordinateRange())) {
//                    Map<String, Map<String, String[]>> mapMap = centerEvaluate3(structureList, calculationTasks,
//                            defaultModel, param, list1, list2);
//                    if (mapMap.size() > 0) {
//                        param.put("userId", userId);
////                        List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                        getInitResultData2(mapMap, defaultModel, calculationTasks, param,
//                                new ArrayList<>());
//                    }
//                }
//            }
        } else if ("0".equals(calculationTasks.getHouseDataFlag())) {
            // 0为单体数据
            if ("0".equals(calculationTasks.getRadio2())) {
                //获取评估区域的省市县
                List<PCC> list = calculationTasks.getList();
                if (PlatformObjectUtils.isNotEmpty(list)) {
                    //获取所有省市县的易损性数据
                    for (PCC pcc : list) {
                        Map<String, Map<String, String[]>> mapMap = centerEvaluate2(pcc, calculationTasks,
                                defaultModel, param, list1, list2);
                        if (mapMap != null && mapMap.size() > 0) {
                            param.put("userId", userId);
                            List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
                            getInitResultData1(mapMap, defaultModel, calculationTasks, pcc, param,
                                    resistEarthquakesPECalculations);
                        }
                    }
                }
            } else if ("1".equals(calculationTasks.getRadio2())) {
                //圈选评估区域
                if (PlatformObjectUtils.isNotEmpty(calculationTasks.getCoordinateRange())) {
                    Map<String, Map<String, String[]>> mapMap = centerEvaluate4(calculationTasks,
                            defaultModel, param, list1, list2);
                    if (mapMap.size() > 0) {
                        param.put("userId", userId);
                        List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
                        getInitResultData2(mapMap, defaultModel, calculationTasks, param,
                                resistEarthquakesPECalculations);
                    }
                }
            }
        }
        //更新计算进度
        if (calculationTasks.getSeismicInputMode().equals("3")) {
            calculationTasksRepository.updateFSProgress(assessId, "评估", "经济损失");
        }
        if (calculationTasks.getSeismicInputMode().equals("4")) {
            calculationTasksRepository.updateCYProgress(assessId, "评估", "经济损失");
        }
        dataCopy(calculationTasks.getId(), list1, list2);
        //刷新指定超图工作空间数据源数据集
        boolean bool = hypergraphService.getWorkspaceReload("fxqh_economic_loss_calculation_pd");

        System.out.println("经济损失-概率评估计算结束，共用时：{}" + (System.currentTimeMillis() - startTime) / 1000 + "s");
    }
//    //计算值
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void calculation(Map<String, Object> param) throws Exception {
//        long startTime = System.currentTimeMillis();
//        String assessId = (String) param.get("taskId");
//
//        //删除上一次数据
//        economicLossPDRepository.deleteCalculation(assessId);
//        String userId = PlatformSessionUtils.getUserId();
//        // 获取当前区县下的所有建筑物；
//        CalculationTasks calculationTasks = calculationTasksService.findById(assessId);
//        //默认的经济模型
//        EconomicLosses defaultModel = economicLossEDRepository.getDefaultModel();
//
//        //人口与建筑物数据
//        List<VillageTownHosPeoEntity> list1 = new ArrayList<>();
//        //建筑物结构重置单价
//        List<BuildingResetUnitPriceEntity> list2 = new ArrayList<>();
//
//        //如果为网格数据
//        if ("1".equals(calculationTasks.getHouseDataFlag())) {
//            //查询版本信息获取dataType
//            List<DictEntityVo> structureList = dictItemService.getDictItemByDictCode("jzwglgwlx");
//            if ("0".equals(calculationTasks.getRadio2())) {
//                //获取评估区域的省市县
//                List<PCC> list = calculationTasks.getList();
//                if (PlatformObjectUtils.isNotEmpty(list)) {
//                    //获取所有省市县的易损性数据
//                    for (PCC pcc : list) {
//                        Map<String, Map<String, String[]>> mapMap = centerEvaluate1(pcc, structureList,
//                                calculationTasks, defaultModel, param, list1, list2);
//                        if (mapMap != null && mapMap.size() > 0) {
//                            param.put("userId", userId);
//                            List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                            getInitResultData1(mapMap, defaultModel, calculationTasks, pcc, param,
//                                    resistEarthquakesPECalculations);
//                        }
//                    }
//                }
//            } else if ("1".equals(calculationTasks.getRadio2())) {
//                //圈选评估区域
//                if (PlatformObjectUtils.isNotEmpty(calculationTasks.getCoordinateRange())) {
//                    Map<String, Map<String, String[]>> mapMap = centerEvaluate3(structureList, calculationTasks,
//                            defaultModel, param, list1, list2);
//                    if (mapMap.size() > 0) {
//                        param.put("userId", userId);
////                        List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                        getInitResultData2(mapMap, defaultModel, calculationTasks, param,
//                                new ArrayList<>());
//                    }
//                }
//            }
//        } else if ("0".equals(calculationTasks.getHouseDataFlag())) {
//            // 0为单体数据
//            if ("0".equals(calculationTasks.getRadio2())) {
//                //获取评估区域的省市县
//                List<PCC> list = calculationTasks.getList();
//                if (PlatformObjectUtils.isNotEmpty(list)) {
//                    //获取所有省市县的易损性数据
//                    for (PCC pcc : list) {
//                        Map<String, Map<String, String[]>> mapMap = centerEvaluate2(pcc, calculationTasks,
//                                defaultModel, param, list1, list2);
//                        if (mapMap != null && mapMap.size() > 0) {
//                            param.put("userId", userId);
//                            List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                            getInitResultData1(mapMap, defaultModel, calculationTasks, pcc, param,
//                                    resistEarthquakesPECalculations);
//                        }
//                    }
//                }
//            } else if ("1".equals(calculationTasks.getRadio2())) {
//                //圈选评估区域
//                if (PlatformObjectUtils.isNotEmpty(calculationTasks.getCoordinateRange())) {
//                    Map<String, Map<String, String[]>> mapMap = centerEvaluate4(calculationTasks,
//                            defaultModel, param, list1, list2);
//                    if (mapMap.size() > 0) {
//                        param.put("userId", userId);
//                        List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                        getInitResultData2(mapMap, defaultModel, calculationTasks, param,
//                                resistEarthquakesPECalculations);
//                    }
//                }
//            }
//        }
//        //更新计算进度
//        if (calculationTasks.getSeismicInputMode().equals("3")) {
//            calculationTasksRepository.updateFSProgress(assessId, "评估", "经济损失");
//        }
//        if (calculationTasks.getSeismicInputMode().equals("4")) {
//            calculationTasksRepository.updateCYProgress(assessId, "评估", "经济损失");
//        }
//        dataCopy(calculationTasks.getId(), list1, list2);
//        //刷新指定超图工作空间数据源数据集
//        boolean bool = hypergraphService.getWorkspaceReload("fxqh_economic_loss_calculation_pd");
//
//        System.out.println("经济损失-概率评估计算结束，共用时：{}" + (System.currentTimeMillis() - startTime) / 1000 + "s");
//    }
//    public void calculation(Map<String, Object> param) throws Exception {
//        long startTime = System.currentTimeMillis();
//        String assessId = (String) param.get("taskId");
//
//        //删除上一次数据
//        economicLossPDRepository.deleteCalculation(assessId);
//        String userId = PlatformSessionUtils.getUserId();
//        // 获取当前区县下的所有建筑物；
//        CalculationTasks calculationTasks = calculationTasksService.findById(assessId);
//        if ("3".equals(calculationTasks.getSeismicInputMode())) {
//            if (PlatformObjectUtils.isEmpty(calculationTasks.getStructuralOccurrenceProgress()) || "0".equals(calculationTasks.getStructuralOccurrenceProgress())) {
//                throw new RuntimeException("请先计算结构破坏-发生概率危险性的确认评估！");
//            }
//        } else if ("4".equals(calculationTasks.getSeismicInputMode())) {
//            if (PlatformObjectUtils.isEmpty(calculationTasks.getStructuralGoBeyondProgress()) || "0".equals(calculationTasks.getStructuralGoBeyondProgress())) {
//                throw new RuntimeException("请先计算结构破坏-超越概率危险性的确认评估！");
//            }
//        } else {
//            throw new RuntimeException("参数错误，请联系管理员！");
//        }
//        // ResistEarthquakesPE resistEarthquakesPE = resistEarthquakesPEService.findById(assessId);
//        //默认的模型
//        EconomicLosses defaultModel = economicLossEDRepository.getDefaultModel();
//
//        ////人口与建筑物数据
//        List<VillageTownHosPeoEntity> list1 = new ArrayList<>();
//        //建筑物结构重置单价
//        List<BuildingResetUnitPriceEntity> list2 = new ArrayList<>();
//
//        //如果为网格数据
//        if ("1".equals(calculationTasks.getHouseDataFlag())) {
//            //查询版本信息获取dataType
//            List<DictEntityVo> structureList = dictItemService.getDictItemByDictCode("jzwglgwlx");
//            if ("0".equals(calculationTasks.getRadio2())) {
//                //获取评估区域的省市县
//                List<PCC> list = calculationTasks.getList();
//                if (PlatformObjectUtils.isNotEmpty(list)) {
//                    //获取所有省市县的易损性数据
//                    for (PCC pcc : list) {
//                        Map<String, Map<String, String[]>> mapMap = centerEvaluate1(pcc, structureList,
//                                calculationTasks, defaultModel, param, list1, list2);
//                        if (mapMap != null && mapMap.size() > 0) {
//                            param.put("userId", userId);
//                            List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                            getInitResultData1(mapMap, defaultModel, calculationTasks, pcc, param,
//                                    resistEarthquakesPECalculations);
//                        }
//                    }
//                }
//            } else if ("1".equals(calculationTasks.getRadio2())) {
//                //圈选评估区域
//                if (PlatformObjectUtils.isNotEmpty(calculationTasks.getCoordinateRange())) {
//                    Map<String, Map<String, String[]>> mapMap = centerEvaluate3(structureList, calculationTasks,
//                            defaultModel, param, list1, list2);
//                    if (mapMap.size() > 0) {
//                        param.put("userId", userId);
//                        List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                        getInitResultData2(mapMap, defaultModel, calculationTasks, param,
//                                resistEarthquakesPECalculations);
//                    }
//                }
//            }
//        } else if ("0".equals(calculationTasks.getHouseDataFlag())) {
//            // 0为单体数据
//            if ("0".equals(calculationTasks.getRadio2())) {
//                //获取评估区域的省市县
//                List<PCC> list = calculationTasks.getList();
//                if (PlatformObjectUtils.isNotEmpty(list)) {
//                    //获取所有省市县的易损性数据
//                    for (PCC pcc : list) {
//                        Map<String, Map<String, String[]>> mapMap = centerEvaluate2(pcc, calculationTasks,
//                                defaultModel, param, list1, list2);
//                        if (mapMap != null && mapMap.size() > 0) {
//                            param.put("userId", userId);
//                            List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                            getInitResultData1(mapMap, defaultModel, calculationTasks, pcc, param,
//                                    resistEarthquakesPECalculations);
//                        }
//                    }
//                }
//            } else if ("1".equals(calculationTasks.getRadio2())) {
//                //圈选评估区域
//                if (PlatformObjectUtils.isNotEmpty(calculationTasks.getCoordinateRange())) {
//                    Map<String, Map<String, String[]>> mapMap = centerEvaluate4(calculationTasks,
//                            defaultModel, param, list1, list2);
//                    if (mapMap.size() > 0) {
//                        param.put("userId", userId);
//                        List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations = resistEarthquakesPEService.queryCalculation1(assessId);
//                        getInitResultData2(mapMap, defaultModel, calculationTasks, param,
//                                resistEarthquakesPECalculations);
//                    }
//                }
//            }
//        }
//        //更新计算进度
//        if (calculationTasks.getSeismicInputMode().equals("3")) {
//            calculationTasksRepository.updateFSProgress(assessId, "评估", "经济损失");
//        }
//        if (calculationTasks.getSeismicInputMode().equals("4")) {
//            calculationTasksRepository.updateCYProgress(assessId, "评估", "经济损失");
//        }
//        dataCopy(calculationTasks.getId(), list1, list2);
//        //刷新指定超图工作空间数据源数据集
//        boolean bool = hypergraphService.getWorkspaceReload("fxqh_economic_loss_calculation_pd");
//
//        System.out.println("经济损失-概率评估计算结束，共用时：{}" + (System.currentTimeMillis() - startTime) / 1000 + "s");
//    }
//    private Map<String, Map<String, String[]>> centerEvaluate1(PCC pcc, List<DictEntityVo> structureList, CalculationTasks calculationTasks
//            , EconomicLosses defaultModel, Map<String, Object> param, List<VillageTownHosPeoEntity> list1
//            , List<BuildingResetUnitPriceEntity> list2) throws Exception {
//        //处理行政区县数据有必要的话
//        handleDistirct(pcc);
//        //人口与建筑物数据
//        VillageTownHosPeoEntity villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCity(pcc.getPid(), pcc.getCid(), pcc.getId(), "");
//        if (PlatformObjectUtils.isEmpty(villageTownHosPeoEntity)) {
//            throw new Exception("该区域内"+pcc.getPpName()+pcc.getCityName()+pcc.getName()+"的人口和建筑物概况未设置");
//        }
//        list1.add(villageTownHosPeoEntity);
//        //建筑物结构重置单价
//        BuildingResetUnitPriceEntity buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvince(pcc.getPid(), pcc.getCid(), pcc.getId());
//        if (PlatformObjectUtils.isEmpty(buildingPriceEntity)) {
//            throw new Exception("该区域内"+pcc.getPpName()+pcc.getCityName()+pcc.getName()+"的建筑物结构重置单价未设置");
//        }
//        list2.add(buildingPriceEntity);
//        if ("0".equals(calculationTasks.getLdPga())) {
//            //烈度   //<结构类型,<设防烈度,<地震烈度,易损性数据>>>
//            Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx =
//                    ysxUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
//            param.put("ldOfYsx", ldOfYsx);
//        } else {
//            //pga
//            System.out.println("开始获取pga易损性数据");
//            Long start = System.currentTimeMillis();
//            param.put("pgaOfYsx", getAndBuildYsxPga(calculationTasks,pcc));
//            System.out.println("获取pga易损性数据结束共花费时间:"+(System.currentTimeMillis()-start)/1000+"s");
//        }
//        //获取所选任务区域合并之后的空间数据
//        String geom = getTaskGeom(pcc);
//
//        Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap = null;
//        //3为发生概率危险性
//        if ("3".equals(calculationTasks.getSeismicInputMode())) {
//            //发生概率危险性的数据
//            List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList1(calculationTasks.getLdPga(), geom,calculationTasks);
//            if (psHazardDataValueList == null || psHazardDataValueList.size() < 1) {
//                throw new RuntimeException("评估未完成，无法获取到任务范围内的发生概率危险性数据!");
//            }
//            //转换发生概率危险性的数据的格式  <格网id,0.01,0.999969>
//            stringMapMap = publicOperateService.buildPsHazardDataValue(psHazardDataValueList).rowMap();
//        } else if ("4".equals(calculationTasks.getSeismicInputMode())) {
//            //4为超越概率危险性
//            if ("0".equals(calculationTasks.getLdPga())) {
//                //烈度
//                stringMapMap = publicOperateService.transition1(geom, calculationTasks.getBeyondProbabilisticVersion(), "0").rowMap();
//            } else if ("1".equals(calculationTasks.getLdPga())) {
//                //pga
//                stringMapMap = publicOperateService.transition2(geom, calculationTasks.getBeyondProbabilisticVersion(), "0").rowMap();
//            } else {
//                throw new RuntimeException("参数2错误，请联系管理员！");
//            }
//        } else {
//            throw new RuntimeException("参数1错误，请联系管理员！");
//        }
//        /**
//         * key: 一个格网
//         * value: 一个格网的数据
//         * Map<String, String[]>
//         *     key: 破坏程度
//         *     value: 建筑物直接经济损失
//         *
//         */
//        Map<String, Map<String, String[]>> mapMap = new HashMap<>();
//        //根据省市县和版本查询13张表数据
//        if (structureList.size() > 0) {
//            for (DictEntityVo vo : structureList) {
//                //烈度的公里网格(获取任务下指定结构类型的网格数据)
//                List<Grid13VO> jggwList = calculationTasksRepository.getGlGwDate(calculationTasks.getId(), vo.getDictItemCode());
//                //根据字典值获取不同结构类型的具体数据并计算
//                if (PlatformObjectUtils.isNotEmpty(jggwList) && jggwList.size() > 0) {
//                    if ("0".equals(calculationTasks.getLdPga())) {
//                        //烈度
//                        getYwData1OfLd(jggwList, villageTownHosPeoEntity, buildingPriceEntity,
//                                defaultModel, stringMapMap, mapMap, param);
//                    } else {
//                        //pga
//                        getYwData1OfPga(jggwList, villageTownHosPeoEntity, buildingPriceEntity,
//                                defaultModel, stringMapMap, mapMap, param);
//                    }
//                }
//            }
//        }
//        return mapMap;
//    }
    private Map<String, Map<String, String[]>> centerEvaluate1(PCC pcc, List<DictEntityVo> structureList, CalculationTasks calculationTasks
            , EconomicLosses defaultModel, Map<String, Object> param, List<VillageTownHosPeoEntity> list1
            , List<BuildingResetUnitPriceEntity> list2) throws Exception {
        //处理行政区县数据有必要的话
        handleDistirct(pcc);
        //人口与建筑物数据
        VillageTownHosPeoEntity villageTownHosPeoEntity = economicLossPDRepository.findByProvinceAndCity(pcc.getPpName(), pcc.getCityName(), pcc.getName(), "");
        if (PlatformObjectUtils.isEmpty(villageTownHosPeoEntity)) {
            throw new Exception("该区域内"+pcc.getPpName()+pcc.getCityName()+pcc.getName()+"的人口和建筑物概况未设置");
        }
        list1.add(villageTownHosPeoEntity);
        //建筑物结构重置单价
        BuildingResetUnitPriceEntity buildingPriceEntity = buildingResetUnitPriceRepository.findByDistrict(pcc.getPpName(), pcc.getCityName(), pcc.getName());
        if (PlatformObjectUtils.isEmpty(buildingPriceEntity)) {
            throw new Exception("该区域内"+pcc.getPpName()+pcc.getCityName()+pcc.getName()+"的建筑物结构重置单价未设置");
        }
        list2.add(buildingPriceEntity);
        if ("0".equals(calculationTasks.getLdPga())) {
            //烈度   //<结构类型,<设防烈度,<地震烈度,易损性数据>>>
            Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx =
                    ysxUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
            param.put("ldOfYsx", ldOfYsx);
        } else {
            //pga
            System.out.println("开始获取pga易损性数据");
            Long start = System.currentTimeMillis();
            param.put("pgaOfYsx", getAndBuildYsxPga(calculationTasks,pcc));
            System.out.println("获取pga易损性数据结束共花费时间:"+(System.currentTimeMillis()-start)/1000+"s");
        }
        //获取所选任务区域合并之后的空间数据
        String geom = getTaskGeom(pcc);

        Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap = null;
        //3为发生概率危险性
        if ("3".equals(calculationTasks.getSeismicInputMode())) {
            //发生概率危险性的数据
            List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList1(calculationTasks.getLdPga(), geom,calculationTasks);
            if (psHazardDataValueList == null || psHazardDataValueList.size() < 1) {
               throw new RuntimeException("评估未完成，无法获取到任务范围内的发生概率危险性数据!");
            }
            //转换发生概率危险性的数据的格式  <格网id,0.01,0.999969>
            stringMapMap = publicOperateService.buildPsHazardDataValue(psHazardDataValueList).rowMap();
        } else if ("4".equals(calculationTasks.getSeismicInputMode())) {
            //4为超越概率危险性
            if ("0".equals(calculationTasks.getLdPga())) {
                //烈度
                stringMapMap = publicOperateService.transition1(geom, calculationTasks.getBeyondProbabilisticVersion(), "0").rowMap();
            } else if ("1".equals(calculationTasks.getLdPga())) {
                //pga
                stringMapMap = publicOperateService.transition2(geom, calculationTasks.getBeyondProbabilisticVersion(), "0").rowMap();
            } else {
                throw new RuntimeException("参数2错误，请联系管理员！");
            }
        } else {
            throw new RuntimeException("参数1错误，请联系管理员！");
        }
        /**
         * key: 一个格网
         * value: 一个格网的数据
         * Map<String, String[]>
         *     key: 破坏程度
         *     value: 建筑物直接经济损失
         *
         */
        Map<String, Map<String, String[]>> mapMap = new HashMap<>();
        //根据省市县和版本查询13张表数据
        if (structureList.size() > 0) {
            for (DictEntityVo vo : structureList) {
                //烈度的公里网格(获取任务下指定结构类型的网格数据)
                List<Grid13VO> jggwList = calculationTasksRepository.getGlGwDate(calculationTasks.getId(), vo.getDictItemCode());
                //根据字典值获取不同结构类型的具体数据并计算
                if (PlatformObjectUtils.isNotEmpty(jggwList) && jggwList.size() > 0) {
                    if ("0".equals(calculationTasks.getLdPga())) {
                        //烈度
                        getYwData1OfLd(jggwList, villageTownHosPeoEntity, buildingPriceEntity,
                                defaultModel, stringMapMap, mapMap, param);
                    } else {
                        //pga
                        getYwData1OfPga(jggwList, villageTownHosPeoEntity, buildingPriceEntity,
                                defaultModel, stringMapMap, mapMap, param);
                    }
                }
            }
        }
        return mapMap;
    }

    //获取所选任务区域合并之后的空间数据
    private String getTaskGeom(PCC pcc) throws BizException {
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        String divisionIds = null;
        try {
            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(pcc.getPpName(), "UTF-8"),
                    URLEncoder.encode(pcc.getCityName(), "UTF-8"), URLEncoder.encode(pcc.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (divisionIds == null) {
            return null;
        }
        String code = null;
        if (areaIdCodeMap == null || areaIdCodeMap.size() < 1) {
            code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
        } else {
            code = areaIdCodeMap.get(divisionIds.split("_")[2]);
        }
        //获取所选任务区域合并之后的空间数据
        return jcsjRestManager.getGeomByCode(code, "3");
    }
    //根据条件判断获取易损性矩阵数据来源并对获取到的数据进行处理
    private JSONArray getAndBuildYsxPga(CalculationTasks calculationTasks,PCC pcc) throws BizException {
        JSONArray pgaOfYsx = null;
        if("0".equals(calculationTasks.getYsxVersion())){
            //国家级的查询承载体的pga数据
            pgaOfYsx =  jcsjRestManager.getPgaOfYsx(pcc.getPpName(), pcc.getCityName(), pcc.getName());
            if(PlatformObjectUtils.isEmpty(pgaOfYsx)){
                throw new RuntimeException("计算未完成，未获取到易损性矩阵信息");
            }
        }else if("2".equals(calculationTasks.getYsxVersion())){
            //自定义群体版的查询本系统的pga数据
            List<YSXMainTable> ysx = ysxRepository.getYSX2(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
            Map<String, List<YSXMainTable>> ysxMap = ysx.stream().collect(Collectors.groupingBy(YSXMainTable::getId));
            List<BasicLibraryVo> finalList = new ArrayList<>();
            ysxMap.forEach((k, v)->{
                //k是主表id，v是这个易损性下的多个值
                BasicLibraryVo vo = new BasicLibraryVo();
                vo.setStructureType(v.get(0).getStructureType1());
                if (PlatformObjectUtils.isNotEmpty(v.get(0).getStructureType2())) {
                    vo.setStructureType1(v.get(0).getStructureType2());
                }
                vo.setDefenseSituation(v.get(0).getFortify());
                List<CurveVo> valueList = PublicOperateService.turningCurve1(v);
                vo.setValueList(valueList);
                finalList.add(vo);
            });
            if(finalList.size()==0){
                throw new RuntimeException("计算未完成，未获取到易损性矩阵信息");
            }
            pgaOfYsx = JSONArray.parseArray(JSON.toJSONString(finalList));
            disrictMap.put(pcc.getPpName()+"-"+pcc.getCityName()+"-"+pcc.getName(),pgaOfYsx);
        }
        return pgaOfYsx;
    }
//    private Map<String, Map<String, String[]>> centerEvaluate1(PCC pcc, List<DictEntityVo> structureList, CalculationTasks calculationTasks
//            , EconomicLosses defaultModel, Map<String, Object> param, List<VillageTownHosPeoEntity> list1
//            , List<BuildingResetUnitPriceEntity> list2) throws Exception {
//        handleDistirct(pcc);
//        //人口与建筑物数据
//        VillageTownHosPeoEntity villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCity(pcc.getPid(), pcc.getCid(), pcc.getId(), "");
//        if (PlatformObjectUtils.isEmpty(villageTownHosPeoEntity)) {
//            throw new Exception("该区域内室内财产损失未设置");
//        }
//        //建筑物结构重置单价
//        BuildingResetUnitPriceEntity buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvince(pcc.getPid(), pcc.getCid(), pcc.getId());
//        list1.add(villageTownHosPeoEntity);
//        list2.add(buildingPriceEntity);
//        if ("0".equals(calculationTasks.getLdPga())) {
//            //烈度
//            Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx =
//                    ysxUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
//            param.put("ldOfYsx", ldOfYsx);
//        } else {
//            //pga
//            JSONArray pgaOfYsx = jcsjRestManager.getPgaOfYsx(pcc.getPpName(), pcc.getCityName(), pcc.getName());
//            param.put("pgaOfYsx", pgaOfYsx);
//        }
//        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
//        String divisionIds = null;
//        try {
//            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(pcc.getPpName(), "UTF-8"),
//                    URLEncoder.encode(pcc.getCityName(), "UTF-8"), URLEncoder.encode(pcc.getName(), "UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        if (divisionIds == null) {
//            return null;
//        }
//        String code = null;
//        if (areaIdCodeMap == null || areaIdCodeMap.size() < 1) {
//            code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
//        } else {
//            code = areaIdCodeMap.get(divisionIds.split("_")[2]);
//        }
//        String geom = jcsjRestManager.getGeomByCode(code, "3");
//        Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap = null;
//        if ("3".equals(calculationTasks.getSeismicInputMode())) {
//            //发生概率危险性的数据
//            List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList(calculationTasks.getLdPga(), geom);
//            if (psHazardDataValueList == null || psHazardDataValueList.size() < 1) {
//                return null;
//            }
//            //转换发生概率危险性的数据的格式
//            stringMapMap = publicOperateService.buildPsHazardDataValue(psHazardDataValueList).rowMap();
//        } else if ("4".equals(calculationTasks.getSeismicInputMode())) {
//            if ("0".equals(calculationTasks.getLdPga())) {
//                //烈度
//                stringMapMap = publicOperateService.transition1(geom, calculationTasks.getBeyondProbabilisticVersion(), "0").rowMap();
//            } else if ("1".equals(calculationTasks.getLdPga())) {
//                //pga
//                stringMapMap = publicOperateService.transition2(geom, calculationTasks.getBeyondProbabilisticVersion(), "0").rowMap();
//            } else {
//                throw new RuntimeException("参数2错误，请联系管理员！");
//            }
//        } else {
//            throw new RuntimeException("参数1错误，请联系管理员！");
//        }
//        /**
//         * key: 一个格网
//         * value: 一个格网的数据
//         * Map<String, String[]>
//         *     key: 破坏程度
//         *     value: 建筑物直接经济损失
//         *
//         */
//        Map<String, Map<String, String[]>> mapMap = new HashMap<>();
//        //根据省市县和版本查询13张表数据
//        if (structureList.size() > 0) {
////             //数据视图条件
////             QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
////             //写入条件版本号
////             queryByVersionParam.setVersionCode(calculationTasks.getHouseData());
//// //                        //获取区县code
//// //                         //0为省市区县1为地图圈选
////             queryByVersionParam.setGeomType(0);
////             queryByVersionParam.setProvince(pcc.getPpName());
////             queryByVersionParam.setCity(pcc.getCityName());
////             queryByVersionParam.setCounty(pcc.getName());
//            for (DictEntityVo vo : structureList) {
//                // queryByVersionParam.setTypeCode(vo.getDictItemCode());
//                // System.out.println(vo.getDictItemCode());
//                //烈度的公里网格
//                List<Grid13VO> jggwList = calculationTasksRepository.getGlGwDate(calculationTasks.getId(), vo.getDictItemCode());
//                //根据字典值获取不同结构类型的具体数据并计算
//                if (PlatformObjectUtils.isNotEmpty(jggwList) && jggwList.size() > 0) {
//                    if ("0".equals(calculationTasks.getLdPga())) {
//                        //烈度
//                        getYwData1OfLd(jggwList, villageTownHosPeoEntity, buildingPriceEntity,
//                                defaultModel, stringMapMap, mapMap, param);
//                    } else {
//                        //pga
//                        getYwData1OfPga(jggwList, villageTownHosPeoEntity, buildingPriceEntity,
//                                defaultModel, stringMapMap, mapMap, param);
//                    }
//                }
//            }
//        }
//        return mapMap;
//    }
    //截取城市、区县的名称
    private void handleDistirct(PCC pcc) {
        //辽宁省-大连市->大连市
        if (org.apache.commons.lang3.StringUtils.isNotBlank(pcc.getCityName())) {
            if (pcc.getCityName().split("-").length == 2) {
                pcc.setCityName(pcc.getCityName().split("-")[1]);
            }
        }
        //辽宁省-大连市-中山区->中山区
        if (org.apache.commons.lang3.StringUtils.isNotBlank(pcc.getName())) {
            if (pcc.getName().split("-").length == 3) {
                pcc.setName(pcc.getName().split("-")[2]);
            }
        }
    }


    /**
     * 将0.04g	0.09g	0.19g	0.38g	0.75g转换成对应的烈度
     */
    private String getRealIntensity(String intensity){
        switch (intensity){
            case "0.04g":
                return "6";
            case "0.09g":
                return "7";
            case "0.19g":
                return "8";
            case "0.38g":
                return "9";
            case "0.75g":
                return "10";
            default: return "";
        }
    }

    private void getYwData1OfLd(List<Grid13VO> jggwList, VillageTownHosPeoEntity villageTownHosPeoEntity,
                                BuildingResetUnitPriceEntity buildingPriceEntity,
                                EconomicLosses defaultModel, Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap,
                                Map<String, Map<String, String[]>> mapMap, Map<String, Object> param) {
        //key:（Ⅵ，Ⅶ，Ⅷ，Ⅸ，Ⅹ）
        Map<String, String[]> map = null;
        //格网id，建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
        String[] strings = null;
        //易损性数据  <结构类型,<设防烈度,<地震烈度，易损性数据>>>
        Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx = (Map<String, Map<String, Map<String, BuildingVulnerability>>>) param.get("ldOfYsx");
        //建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
        BigDecimal structureDirectLosses = BigDecimal.ZERO;
        //一个obj就是一个网格的一个结构类型的数据
        for (Grid13VO obj : jggwList) {
            //一个公里网格下的危险性数据，年平均发生概率，key为X轴(im)，value为Y轴(年平均发生概率)
            if(org.apache.commons.lang3.StringUtils.isBlank(obj.getExtends1())){
                continue;
            }
            //概率危险性数据
            Map<List<String>, List<BigDecimal>> listListMap = stringMapMap.get(obj.getExtends1());
            if (mapMap.containsKey(obj.getGeom())) {
                map = mapMap.get(obj.getGeom());
            } else {
                map = new HashMap<>();
            }
            //总面积当前坐标总面积
            BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
            //ysxData的第一个key，结构类型
            String mapKey = "";
            //获取对应易损性结构类型
            if (!"城镇钢混结构".equals(obj.getStructureType())) {
                mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
            } else {
                //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
                if (obj.getF31() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                } else if (obj.getF17F30() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                } else if (obj.getF11F16() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                } else if (obj.getF7F10() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                } else {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
                }
                if ("剪力墙结构".equals(mapKey)) {
                    mapKey = "钢筋混凝土结构-" + mapKey;
                }
            }
            //当前结构的易损性数据 <设防烈度,<地震烈度，易损性数据>>
            Map<String, Map<String, BuildingVulnerability>> sfIntensityMap = ldOfYsx.get(mapKey);
            if (sfIntensityMap == null || sfIntensityMap.size() < 1) {
                continue;
            }
            //该数据所具备的设防烈度和对应的烈度面积占比结构 <设防烈度，去掉百分号小数格式的面积占比>
            Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
            //建筑物结构的重置单价
            BigDecimal buildingPrice = BigDecimal.ZERO;
            if (buildingPriceEntity != null) {
                switch (mapKey) {
                    case "砌体结构-砖混结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
                        break;
                    case "钢筋混凝土结构-剪力墙结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
                        break;
                    case "钢结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
                        break;
                    case "木结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
                        break;
                    case "其他":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
                        break;
                    case "土木结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
                        break;
                    case "钢筋混凝土结构-框架结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
                        break;
                    case "钢筋混凝土结构-框架-剪力墙结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
                        break;
                }
            }
            //地区室内财产（元/每平米）
            BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
            if (obj.getStructureType().contains("城镇")) {
                dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
            } else {
                dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
            }
            //概率危险性数据
            if (listListMap != null && listListMap.size() > 0) {
                BigDecimal area = BigDecimal.ZERO;
                List<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
                //imList [0.04g	0.09g	0.19g	0.38g	0.75g]
                for (List<String> imList : listListMap.keySet()) {
                    //遍历烈度
                    for (int zz=0;zz<imList.size();zz++) {
                        String im = imList.get(zz);
                        BigDecimal imValue = values.get(0).get(zz);
                        String realIntensity = getRealIntensity(im);
                        //数据的各个破坏程度的面积  <设防烈度，去掉百分号小数格式的面积占比>
                        for (Map.Entry<String, BigDecimal> entry : intensitAreaMap.entrySet()) {
                            //设防烈度
                            String sfIntensity = entry.getKey();
                            //设防烈度对应的面积
                            BigDecimal sfIntensityArea = totalArea.multiply(entry.getValue());
                            //易损性数据下设防烈度对应的数据 <地震烈度，易损性数据>
                            Map<String, BuildingVulnerability> vulnerabilityList = null;
                            try {
                                vulnerabilityList = sfIntensityMap.get(sfIntensity);
                            } catch (NullPointerException e) {
                                e.printStackTrace();
                            }
                            //4个破坏程度（轻微，中等，严重，倒塌）
                            for (int j = 1; j < 5; j++) {
                                String extreme = null;
                                switch (j) {
                                    case 1:
                                        extreme = "pgcd2";
                                        break;
                                    case 2:
                                        extreme = "pgcd3";
                                        break;
                                    case 3:
                                        extreme = "pgcd4";
                                        break;
                                    case 4:
                                        extreme = "pgcd5";
                                }
                                if (map.containsKey(extreme)) {
                                    strings = map.get(extreme);
                                } else {
                                    strings = new String[]{obj.getExtends1(), BigDecimal.ZERO + ""};
                                }

                                if (vulnerabilityList != null && vulnerabilityList.size() > 0) {
                                    BuildingVulnerability buildingVulnerability = vulnerabilityList.get(realIntensity);
                                    if (buildingVulnerability != null) {
                                        switch (j) {
                                            case 1:
                                                //轻微破坏面积
//                                                area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSlight()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                area = sfIntensityArea.multiply(buildingVulnerability.getSlight()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue);
                                                break;
                                            case 2:
                                                //中等破坏面积
//                                                area = area.add(sfIntensityArea.multiply(buildingVulnerability.getMid()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                area = sfIntensityArea.multiply(buildingVulnerability.getMid()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue);
                                                break;
                                            case 3:
                                                //严重破坏面积
//                                                area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSerious()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                area = sfIntensityArea.multiply(buildingVulnerability.getSerious()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue);
                                                break;
                                            case 4:
                                                //损坏面积
//                                                area = area.add(sfIntensityArea.multiply(buildingVulnerability.getDestroy()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                area = sfIntensityArea.multiply(buildingVulnerability.getDestroy()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue);
                                        }
                                    }
                                }
                                // //多除以100-----------待修改
                                // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                                //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
                                strings[1] = new BigDecimal(strings[1]).add(getStructureLossess1(obj.getStructureType()
                                        , area, buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
                                map.put(extreme, strings);
                                mapMap.put(obj.getGeom(), map);
                            }
                        }
                    }
                }

            }

        }
    }
//    private void getYwData1OfLd(List<Grid13VO> jggwList, VillageTownHosPeoEntity villageTownHosPeoEntity,
//                                BuildingResetUnitPriceEntity buildingPriceEntity,
//                                EconomicLosses defaultModel, Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap,
//                                Map<String, Map<String, String[]>> mapMap, Map<String, Object> param) {
//        //key:（Ⅵ，Ⅶ，Ⅷ，Ⅸ，Ⅹ）
//        Map<String, String[]> map = null;
//        //格网id，建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
//        String[] strings = null;
//        //易损性数据  <结构类型,<设防烈度,<地震烈度，易损性数据>>>
//        Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx = (Map<String, Map<String, Map<String, BuildingVulnerability>>>) param.get("ldOfYsx");
//        //建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
//        BigDecimal structureDirectLosses = BigDecimal.ZERO;
//        //一个obj就是一个网格的一个结构类型的数据
//        for (Grid13VO obj : jggwList) {
//            //一个公里网格下的危险性数据，年平均发生概率，key为X轴(im)，value为Y轴(年平均发生概率)
//            if(org.apache.commons.lang3.StringUtils.isBlank(obj.getExtends1())){
//                continue;
//            }
//            //概率危险性数据
//            Map<List<String>, List<BigDecimal>> listListMap = stringMapMap.get(obj.getExtends1());
//            if (mapMap.containsKey(obj.getGeom())) {
//                map = mapMap.get(obj.getGeom());
//            } else {
//                map = new HashMap<>();
//            }
//            //总面积当前坐标总面积
//            BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
//            //ysxData的第一个key，结构类型
//            String mapKey = "";
//            //获取对应易损性结构类型
//            if (!"城镇钢混结构".equals(obj.getStructureType())) {
//                mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
//            } else {
//                //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
//                if (obj.getF31() > 0) {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
//                } else if (obj.getF17F30() > 0) {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
//                } else if (obj.getF11F16() > 0) {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
//                } else if (obj.getF7F10() > 0) {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
//                } else {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
//                }
//                if ("剪力墙结构".equals(mapKey)) {
//                    mapKey = "钢筋混凝土结构-" + mapKey;
//                }
//            }
//            //当前结构的易损性数据 <设防烈度,<地震烈度，易损性数据>>
//            Map<String, Map<String, BuildingVulnerability>> sfIntensityMap = ldOfYsx.get(mapKey);
//            if (sfIntensityMap == null || sfIntensityMap.size() < 1) {
//                continue;
//            }
//            //该数据所具备的设防烈度和对应的烈度面积占比结构 <设防烈度，去掉百分号小数格式的面积占比>
//            Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
//            //建筑物结构的重置单价
//            BigDecimal buildingPrice = BigDecimal.ZERO;
//            if (buildingPriceEntity != null) {
//                switch (mapKey) {
//                    case "砌体结构-砖混结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
//                        break;
//                    case "钢筋混凝土结构-剪力墙结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
//                        break;
//                    case "钢结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
//                        break;
//                    case "木结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
//                        break;
//                    case "其他":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
//                        break;
//                    case "土木结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
//                        break;
//                    case "钢筋混凝土结构-框架结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
//                        break;
//                    case "钢筋混凝土结构-框架-剪力墙结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
//                        break;
//                }
//            }
//            //地区室内财产（元/每平米）
//            BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
//            if (obj.getStructureType().contains("城镇")) {
//                dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
//            } else {
//                dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
//            }
//            //数据的各个破坏程度的面积  <设防烈度，去掉百分号小数格式的面积占比>
//            for (Map.Entry<String, BigDecimal> entry : intensitAreaMap.entrySet()) {
//                //设防烈度
//                String sfIntensity = entry.getKey();
//                //设防烈度对应的面积
//                BigDecimal sfIntensityArea = totalArea.multiply(entry.getValue());
//                //易损性数据下设防烈度对应的数据
//                Map<String, BuildingVulnerability> vulnerabilityList = null;
//                try {
//                    vulnerabilityList = sfIntensityMap.get(sfIntensity);
//                } catch (NullPointerException e) {
//                    e.printStackTrace();
//                }
//                //4个破坏程度（轻微，中等，严重，倒塌）
//                for (int j = 1; j < 5; j++) {
//                    String extreme = null;
//                    switch (j) {
//                        case 1:
//                            extreme = "pgcd2";
//                            break;
//                        case 2:
//                            extreme = "pgcd3";
//                            break;
//                        case 3:
//                            extreme = "pgcd4";
//                            break;
//                        case 4:
//                            extreme = "pgcd5";
//                    }
//                    if (map.containsKey(extreme)) {
//                        strings = map.get(extreme);
//                    } else {
//                        strings = new String[]{obj.getExtends1(), BigDecimal.ZERO + ""};
//                    }
//                    //概率危险性数据
//                    if (listListMap != null && listListMap.size() > 0) {
//                        BigDecimal area = BigDecimal.ZERO;
//                        //imList [0.04g	0.09g	0.19g	0.38g	0.75g]
//                        for (List<String> imList : listListMap.keySet()) {
//                            //遍历烈度
//                            for (String im : imList) {
//                                switch (im) {
//                                    case "Ⅴ":
//                                    case "Ⅵ":
//                                        im = "6";
//                                        break;
//                                    case "Ⅶ":
//                                        im = "7";
//                                        break;
//                                    case "Ⅷ":
//                                        im = "8";
//                                        break;
//                                    case "Ⅸ":
//                                        im = "9";
//                                        break;
//                                    case "Ⅹ":
//                                    case "Ⅺ":
//                                    case "Ⅻ":
//                                        im = "10";
//                                        break;
//                                }
//                                if (vulnerabilityList != null && vulnerabilityList.size() > 0) {
//                                    BuildingVulnerability buildingVulnerability = vulnerabilityList.get(im);
//                                    if (buildingVulnerability != null) {
//                                        switch (j) {
//                                            case 1:
//                                                //轻微破坏面积
//                                                area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSlight()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
//                                                break;
//                                            case 2:
//                                                //中等破坏面积
//                                                area = area.add(sfIntensityArea.multiply(buildingVulnerability.getMid()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
//                                                break;
//                                            case 3:
//                                                //严重破坏面积
//                                                area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSerious()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
//                                                break;
//                                            case 4:
//                                                //损坏面积
//                                                area = area.add(sfIntensityArea.multiply(buildingVulnerability.getDestroy()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
//                                        }
//                                        break;
//                                    }
//                                }
//                            }
//                        }
//                        // //多除以100-----------待修改
//                        // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
//                        //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
//                        strings[1] = new BigDecimal(strings[1]).add(getStructureLossess1(obj.getStructureType()
//                                , area, buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
//                    }
//                    map.put(extreme, strings);
//                    mapMap.put(obj.getGeom(), map);
//                }
//            }
//        }
//    }

    private void getYwData1OfPga(List<Grid13VO> jggwList, VillageTownHosPeoEntity villageTownHosPeoEntity,
                                 BuildingResetUnitPriceEntity buildingPriceEntity,
                                 EconomicLosses defaultModel, Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap,
                                 Map<String, Map<String, String[]>> mapMap, Map<String, Object> param) {
        //key:（Ⅵ，Ⅶ，Ⅷ，Ⅸ，Ⅹ）
        String[] strings = null;
        JSONArray pgaOfYsx = (JSONArray) param.get("pgaOfYsx");
        if (pgaOfYsx == null || pgaOfYsx.size() < 1) {
            return;
        }

        //建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
        //一个obj就是一个网格的一个结构类型的数据
        for (int jj=0;jj<jggwList.size();jj++) {
            Map<String, String[]> map = null;
            Grid13VO obj = jggwList.get(jj);
            if(org.apache.commons.lang3.StringUtils.isBlank(obj.getExtends1())){
                continue;
            }
            Map<List<String>, List<BigDecimal>> listListMap = stringMapMap.get(obj.getExtends1());
            if (mapMap.containsKey(obj.getGeom())) {
                map = mapMap.get(obj.getGeom());
            } else {
                map = new HashMap<>();
            }
            //总面积当前坐标总面积
            BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
            //ysxData的第一个key，结构类型
            String mapKey = "";
            //获取对应易损性结构类型
            if (!"城镇钢混结构".equals(obj.getStructureType())) {
                mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
            } else {
                //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
                if (obj.getF31() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                } else if (obj.getF17F30() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                } else if (obj.getF11F16() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                } else if (obj.getF7F10() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                } else {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
                }
                if ("剪力墙结构".equals(mapKey)) {
                    mapKey = "钢筋混凝土结构-" + mapKey;
                }
            }
            //该数据所具备的设防烈度和对应的烈度面积占比结构
            Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
            //建筑物结构的重置单价
            BigDecimal buildingPrice = BigDecimal.ZERO;
            if (buildingPriceEntity != null) {
                switch (mapKey) {
                    case "砌体结构-砖混结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
                        break;
                    case "钢筋混凝土结构-剪力墙结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
                        break;
                    case "钢结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
                        break;
                    case "木结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
                        break;
                    case "其他":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
                        break;
                    case "土木结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
                        break;
                    case "钢筋混凝土结构-框架结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
                        break;
                    case "钢筋混凝土结构-框架-剪力墙结构":
                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
                        break;
                }
            }
            //地区室内财产（元/每平米）
            BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
            if (obj.getStructureType().contains("城镇")) {
                dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
            } else {
                dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
            }
            //数据的各个破坏程度的面积
            for (Map.Entry<String, BigDecimal> entry : intensitAreaMap.entrySet()) {
                //设防烈度
                String sfIntensity = entry.getKey();
                //设防烈度对应的面积
                BigDecimal sfIntensityArea = totalArea.multiply(entry.getValue());
                JSONArray jsonArray = null;
                String[] split = mapKey.split("-");
                if (split.length == 2) {
                    for (int i = 0; i < pgaOfYsx.size(); i++) {
                        JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
                        if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("structureType1").equals(split[1])
                                && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
                            jsonArray = jsonObject.getJSONArray("valueList");
                            break;
                        }
                    }
                } else {
                    for (int i = 0; i < pgaOfYsx.size(); i++) {
                        JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
                        if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
                            jsonArray = jsonObject.getJSONArray("valueList");
                            break;
                        }
                    }
                }
                if (jsonArray == null) {
                    continue;
                }
                Map<Object, List<Object>> groupBySiteType = jsonArray.stream().sorted(
                        Comparator.comparingLong(
                                // 根据对象中的ID进行排序
                                e -> JSONObject.parseObject(e.toString()).getIntValue("sort")
                        )
                ).collect(Collectors.groupingBy(item -> JSON.parseObject(item.toString()).get("im")));
                //4个破坏程度（轻微，中等，严重，倒塌）
                for (int j = 1; j < 5; j++) {
                    String extreme = null;
                    String extreme1 = null;
                    switch (j) {
                        case 1:
                            extreme = "pgcd2";
                            extreme1 = "轻微破坏";
                            break;
                        case 2:
                            extreme = "pgcd3";
                            extreme1 = "中等破坏";
                            break;
                        case 3:
                            extreme = "pgcd4";
                            extreme1 = "严重破坏";
                            break;
                        case 4:
                            extreme = "pgcd5";
                            extreme1 = "倒塌";
                    }
                    if (map.containsKey(extreme)) {
                        strings = map.get(extreme);
                    } else {
                        strings = new String[]{obj.getExtends1(), BigDecimal.ZERO + ""};
                    }
//                    for (int i = 0; i < jsonArray.size(); i++) {
//                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//                        if (jsonObject1.getString("destructiveState").equals(extreme1)) {
//                            jsonObject = jsonObject1;
//                            break;
//                        }
//                    }
//                    JSONObject jsonObject = null;
//                    try{
//                        jsonObject = jsonArray.getJSONObject(j);
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//                    if (jsonObject != null) {
                        if (PlatformObjectUtils.isNotEmpty(listListMap)) {
                            BigDecimal area = BigDecimal.ZERO;
                            List<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
                            for (List<String> imList : listListMap.keySet()) {
                                //imList相当于烈度
                                for (int zz = 0;zz<imList.size();zz++) {
                                    String im = imList.get(zz);
                                    BigDecimal value = values.get(0).get(zz);
                                    if("0.9".equals(im)){
                                        //特殊情况 如遇到0.9的按照0.8的值计算
                                        im = "0.8";
                                    }
                                    List<Object> objectList = groupBySiteType.get(new BigDecimal(im));
                                    if(objectList==null){
                                       continue;
                                    }
                                    Map<String, List<CurveVo>> breakStateMap = jsonToVoMap(objectList);
                                     //设防面积为0 0*任何数都是0 所以就没必要获取易损性矩阵值直接加0即可
                                    if(sfIntensityArea.compareTo(BigDecimal.ZERO)==0){
                                        area = area.add(sfIntensityArea);
                                    }else{
                                        BigDecimal funtionValue = getValue(breakStateMap,extreme1);
                                        area = area.add(sfIntensityArea.multiply(value).multiply(funtionValue));
//                                        BigDecimal mr = jsonObject.getBigDecimal("mr");
//                                        BigDecimal br = jsonObject.getBigDecimal("br");
//                                        if(!functionMap.containsKey(sfIntensity+"_"+extreme+"_"+mr+"_"+br+"_"+im)){
//                                            funtionValue = publicOperateService.getFuntionValue(jsonObject, im);
//                                            functionMap.put(sfIntensity+"_"+extreme+"_"+mr+"_"+br+"_"+im,funtionValue);
//                                        }else{
//                                            funtionValue = functionMap.get(sfIntensity+"_"+extreme+"_"+mr+"_"+br+"_"+im);
//                                        }
                                    }
                                }
                            }
                            //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失  面积为0 0乘以任何数都是0 所以不必求经济损失的值直接加0即可
                            if(area.compareTo(BigDecimal.ZERO)==0){
                                if(strings==null){
                                    strings[1] = new BigDecimal(strings[1]).add(BigDecimal.ZERO) + "";
                                }
                            }else{
                                strings[1] = new BigDecimal(strings[1]).add(getStructureLossess1(obj.getStructureType(),
                                        area, buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
                            }
                        }
                    //}
                    map.put(extreme, strings);
                }
            }
            mapMap.put(obj.getGeom(), map);
        }
    }

    private Map<String, List<CurveVo>> jsonToVoMap( List<Object> objectList){
        List<CurveVo> vos = new ArrayList<>();
        for (Object o : objectList) {
            JSONObject json = (JSONObject) o;
            CurveVo vo = JSON.parseObject(json.toJSONString(), CurveVo.class);
            vos.add(vo);
        }
        return vos.stream().collect(Collectors.groupingBy(CurveVo::getBreakState));
    }
    private BigDecimal getValue(Map<String, List<CurveVo>> breakStateMap,String extreme1){
        BigDecimal value = null;
        switch (extreme1) {
            case "轻微破坏":
                value = breakStateMap.get(extreme1).get(0).getFim().subtract(breakStateMap.get("中等破坏").get(0).getFim()).setScale(6,RoundingMode.HALF_DOWN);
                break;
            case "中等破坏":
                value = breakStateMap.get(extreme1).get(0).getFim().subtract(breakStateMap.get("严重破坏").get(0).getFim()).setScale(6,RoundingMode.HALF_DOWN);
                break;
            case "严重破坏":
                value = breakStateMap.get(extreme1).get(0).getFim().subtract(breakStateMap.get("倒塌").get(0).getFim()).setScale(6,RoundingMode.HALF_DOWN);
                break;
            case "倒塌":
                value = breakStateMap.get(extreme1).get(0).getFim();
                break;
            default:
        }
        return value;
    }
//    private void getYwData1OfPga(List<Grid13VO> jggwList, VillageTownHosPeoEntity villageTownHosPeoEntity,
//                                 BuildingResetUnitPriceEntity buildingPriceEntity,
//                                 EconomicLosses defaultModel, Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap,
//                                 Map<String, Map<String, String[]>> mapMap, Map<String, Object> param) {
//        //key:（Ⅵ，Ⅶ，Ⅷ，Ⅸ，Ⅹ）
//        Map<String, String[]> map = null;
//        String[] strings = null;
//        JSONArray pgaOfYsx = (JSONArray) param.get("pgaOfYsx");
//        if (pgaOfYsx == null || pgaOfYsx.size() < 1) {
//            return;
//        }
//        //建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
//        BigDecimal structureDirectLosses = BigDecimal.ZERO;
//        //一个obj就是一个网格的一个结构类型的数据
//        for (Grid13VO obj : jggwList) {
//            // if("3d33788670394fdf9120197f048b9854".equals(obj.getExtends1())){
//            //     System.out.println();
//            // }else {
//            //     continue;
//            // }
//            //如果总面积是0,就不用继续进行了
//            // if (obj.getTotalArea() == null || obj.getTotalArea() == 0.0) {
//            //     continue;
//            // }
//            if(org.apache.commons.lang3.StringUtils.isBlank(obj.getExtends1())){
//                continue;
//            }
//            Map<List<String>, List<BigDecimal>> listListMap = stringMapMap.get(obj.getExtends1());
//            if (mapMap.containsKey(obj.getGeom())) {
//                map = mapMap.get(obj.getGeom());
//            } else {
//                map = new HashMap<>();
//            }
//            //总面积当前坐标总面积
//            BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
//            //ysxData的第一个key，结构类型
//            String mapKey = "";
//            //获取对应易损性结构类型
//            if (!"城镇钢混结构".equals(obj.getStructureType())) {
//                mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
//            } else {
//                //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
//                if (obj.getF31() > 0) {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
//                } else if (obj.getF17F30() > 0) {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
//                } else if (obj.getF11F16() > 0) {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
//                } else if (obj.getF7F10() > 0) {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
//                } else {
//                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
//                }
//                if ("剪力墙结构".equals(mapKey)) {
//                    mapKey = "钢筋混凝土结构-" + mapKey;
//                }
//            }
//            //该数据所具备的设防烈度和对应的烈度面积占比结构
//            Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
//            //建筑物结构的重置单价
//            BigDecimal buildingPrice = BigDecimal.ZERO;
//            if (buildingPriceEntity != null) {
//                switch (mapKey) {
//                    case "砌体结构-砖混结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
//                        break;
//                    case "钢筋混凝土结构-剪力墙结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
//                        break;
//                    case "钢结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
//                        break;
//                    case "木结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
//                        break;
//                    case "其他":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
//                        break;
//                    case "土木结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
//                        break;
//                    case "钢筋混凝土结构-框架结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
//                        break;
//                    case "钢筋混凝土结构-框架-剪力墙结构":
//                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
//                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
//                        break;
//                }
//            }
//            //地区室内财产（元/每平米）
//            BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
//            if (obj.getStructureType().contains("城镇")) {
//                dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
//            } else {
//                dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
//            }
//            //数据的各个破坏程度的面积
//            for (Map.Entry<String, BigDecimal> entry : intensitAreaMap.entrySet()) {
//                //设防烈度
//                String sfIntensity = entry.getKey();
//                //设防烈度对应的面积
//                BigDecimal sfIntensityArea = totalArea.multiply(entry.getValue());
//                JSONArray jsonArray = null;
//                String[] split = mapKey.split("-");
//                if (split.length == 2) {
//                    for (int i = 0; i < pgaOfYsx.size(); i++) {
//                        JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
//                        if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("structureType1").equals(split[1])
//                                && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
//                            jsonArray = jsonObject.getJSONArray("valueList");
//                            break;
//                        }
//                    }
//                } else {
//                    for (int i = 0; i < pgaOfYsx.size(); i++) {
//                        JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
//                        if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
//                            jsonArray = jsonObject.getJSONArray("valueList");
//                            break;
//                        }
//                    }
//                }
//                if (jsonArray == null) {
//                    continue;
//                }
//                //4个破坏程度（轻微，中等，严重，倒塌）
//                for (int j = 1; j < 5; j++) {
//                    JSONObject jsonObject = null;
//                    String extreme = null;
//                    String extreme1 = null;
//                    switch (j) {
//                        case 1:
//                            extreme = "pgcd2";
//                            extreme1 = "轻微破坏";
//                            break;
//                        case 2:
//                            extreme = "pgcd3";
//                            extreme1 = "中等破坏";
//                            break;
//                        case 3:
//                            extreme = "pgcd4";
//                            extreme1 = "严重破坏";
//                            break;
//                        case 4:
//                            extreme = "pgcd5";
//                            extreme1 = "倒塌";
//                    }
//                    if (map.containsKey(extreme)) {
//                        strings = map.get(extreme);
//                    } else {
//                        strings = new String[]{obj.getExtends1(), BigDecimal.ZERO + ""};
//                    }
//                    for (int i = 0; i < jsonArray.size(); i++) {
//                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//                        if (jsonObject1.getString("destructiveState").equals(extreme1)) {
//                            jsonObject = jsonObject1;
//                            break;
//                        }
//                    }
//                    if (jsonObject != null) {
//                        if (PlatformObjectUtils.isNotEmpty(listListMap)) {
//                            BigDecimal area = BigDecimal.ZERO;
//                            List<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
//                            for (List<String> imList : listListMap.keySet()) {
//                                for (int zz = 0;zz<imList.size();zz++) {
//                                    String im = imList.get(zz);
//                                    BigDecimal imValue = values.get(0).get(zz);
//                                    BigDecimal funtionValue = publicOperateService.getFuntionValue(jsonObject, im);
//                                    //area = area.add(sfIntensityArea.multiply(funtionValue).multiply(imValue).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
//                                    area = area.add(sfIntensityArea.multiply(funtionValue).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
//                                }
//                            }
//                            // //多除以100-----------待修改
//                            // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
//                            //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
//                            strings[1] = new BigDecimal(strings[1]).add(getStructureLossess1(obj.getStructureType(),
//                                    area, buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
//                        }
//                    }
//
//                    map.put(extreme, strings);
//                    mapMap.put(obj.getGeom(), map);
//                }
//            }
//        }
//    }

    private Table buildStructureTable() {
        Table<String, String, String> ysxTable = HashBasedTable.create();
        ysxTable.put("城镇砌体结构", "城镇砌体结构", "砌体结构-砖混结构");
        ysxTable.put("城镇钢混结构", "19", "剪力墙结构");
        ysxTable.put("城镇钢结构", "城镇钢结构", "钢结构");
        ysxTable.put("城镇木结构", "城镇木结构", "木结构");
        ysxTable.put("城镇其他结构", "城镇其他结构", "其他");
        ysxTable.put("农村砌体结构", "农村砌体结构", "砌体结构-砖混结构");
        ysxTable.put("农村土木（石木）结构", "农村土木（石木）结构", "土木结构");
        ysxTable.put("农村底部框架结构", "农村底部框架结构", "砌体结构-砖混结构");
        ysxTable.put("农村木（竹）结构", "农村木（竹）结构", "木结构");
        ysxTable.put("农村混杂结构", "农村混杂结构", "其他");
        ysxTable.put("农村钢混结构", "农村钢混结构", "钢筋混凝土结构-框架结构");
        ysxTable.put("农村钢结构", "农村钢结构", "钢结构");
        ysxTable.put("农村其他结构", "农村其他结构", "其他");
        ysxTable.put("城镇钢混结构", "8", "钢筋混凝土结构-框架结构");
        ysxTable.put("城镇钢混结构", "18", "钢筋混凝土结构-框架-剪力墙结构");
        return ysxTable;
    }

    private Map<String, BigDecimal> getIntensitArea(Grid13VO obj) {
        Map<String, BigDecimal> map = new HashMap<>();
        if (!(obj.getSfIntensity9() == null || obj.getSfIntensity9() == 0)) {
            map.put("9度", BigDecimal.valueOf(obj.getSfIntensity9()).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_UP));
        }
        if (!(obj.getSfIntensity8() == null || obj.getSfIntensity8() == 0)) {
            map.put("8度", BigDecimal.valueOf(obj.getSfIntensity8()).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_UP));
        }
        if (!(obj.getSfIntensity7() == null || obj.getSfIntensity7() == 0)) {
            map.put("7度", BigDecimal.valueOf(obj.getSfIntensity7()).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_UP));
        }
        if (!(obj.getSfIntensity6() == null || obj.getSfIntensity6() == 0)) {
            map.put("6度", BigDecimal.valueOf(obj.getSfIntensity6()).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_UP));
        }
        if (map.size() < 1) {
            map.put("未设防", BigDecimal.valueOf(1));
        } else {
            if (!(obj.getSfIntensity() == null || obj.getSfIntensity() == 0)) {
                map.put("未设防", BigDecimal.valueOf(obj.getSfIntensity()).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_UP));
            }
        }
        return map;
    }

    /**
     * 获取每类建筑结构的建筑物直接经济损失
     */
    private BigDecimal getStructureLossess1(String structureType, BigDecimal area, BigDecimal buildingPrice,
                                            EconomicLosses model, BigDecimal indoorPrice, String extreme) {
        //各类损失比
        BigDecimal basic = new BigDecimal(0);
        switch (structureType) {
            case "城镇钢混结构":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight4();
                        break;
                    case "pgcd3":
                        basic = model.getMid4();
                        break;
                    case "pgcd4":
                        basic = model.getSerious4();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy4();
                        break;
                }
                break;
            case "城镇钢结构":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight2();
                        break;
                    case "pgcd3":
                        basic = model.getMid2();
                        break;
                    case "pgcd4":
                        basic = model.getSerious2();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy2();
                        break;
                }
                break;
            case "城镇砌体结构":
            case "农村底部框架结构":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight5();
                        break;
                    case "pgcd3":
                        basic = model.getMid5();
                        break;
                    case "pgcd4":
                        basic = model.getSerious5();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy5();
                        break;
                }
                break;
            case "城镇木结构":
            case "城镇其他结构":
            case "农村砌体结构":
            case "农村钢混结构":
            case "农村钢结构":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight3();
                        break;
                    case "pgcd3":
                        basic = model.getMid3();
                        break;
                    case "pgcd4":
                        basic = model.getSerious3();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy3();
                        break;
                }
                break;
            case "农村土木（石木）结构":
            case "农村木（竹）结构":
            case "农村混杂结构":
            case "农村其他结构":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight9();
                        break;
                    case "pgcd3":
                        basic = model.getMid9();
                        break;
                    case "pgcd4":
                        basic = model.getSerious9();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy9();
                        break;
                }
                break;
        }
        //得到建筑物结构经济损失
        BigDecimal structureLossess = model.getStructureLossess();
        BigDecimal lossess = area.multiply(buildingPrice).multiply(basic).multiply(structureLossess).divide(new BigDecimal(1000000), 10, BigDecimal.ROUND_HALF_UP);
        //得到建筑物室内财产经济损失
        BigDecimal indoorLossess = area.multiply(indoorPrice).multiply(basic).multiply(structureLossess).divide(new BigDecimal(1000000), 10, BigDecimal.ROUND_HALF_UP);
        //建筑物直接经济损失
        BigDecimal sum = lossess.add(indoorLossess);
        return sum;
    }

    private void dataCopy(String taskId, List<VillageTownHosPeoEntity> list1, List<BuildingResetUnitPriceEntity> list2) {
        calculationTasksService.delFxqhHosPeoTask(taskId);
        calculationTasksService.delFxqhBuildingPriceTask(taskId);
        FxqhHosPeoTaskEntity entity1 = null;
        for (VillageTownHosPeoEntity entity : list1) {
            entity1 = new FxqhHosPeoTaskEntity();
            UpdateUtil.copyNullProperties(entity, entity1);
            entity1.setUuid(UUIDGenerator.getUUID());
            entity1.setTaskId(taskId);
            calculationTasksService.saveFxqhHosPeoTask(entity1);
        }
        FxqhBuildingPriceTaskEntity entity2 = null;
        for (BuildingResetUnitPriceEntity entity : list2) {
            entity2 = new FxqhBuildingPriceTaskEntity();
            UpdateUtil.copyNullProperties(entity, entity2);
            entity2.setUuid(UUIDGenerator.getUUID());
            entity2.setTaskId(taskId);
            calculationTasksService.saveFxqhBuildingPriceTask(entity2);
        }
    }


    private void getInitResultData1(Map<String, Map<String, String[]>> mapMap, EconomicLosses defaultModel
            , CalculationTasks calculationTasks, PCC pcc, Map<String, Object> param
            , List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations) {
        List<EconomicLossPDCalculation> list = new ArrayList<>();
        for (Map.Entry<String, Map<String, String[]>> entry1 : mapMap.entrySet()) {
            String key1 = entry1.getKey();
            for (Map.Entry<String, String[]> entry2 : entry1.getValue().entrySet()) {
                String key2 = entry2.getKey();//破坏程度
                String extends1 = entry2.getValue()[0];
                BigDecimal structureDirectLosses = new BigDecimal(entry2.getValue()[1]);//建筑物直接经济损失
                //生命线经济损失评估
                BigDecimal lifeLosses = structureDirectLosses.divide(defaultModel.getLifeRatio1(), 4, BigDecimal.ROUND_DOWN).multiply(defaultModel.getLifeRatio2());
                //其他经济损失评估
                BigDecimal otherLosses = structureDirectLosses.divide(defaultModel.getOtherRatio1(), 4, BigDecimal.ROUND_DOWN).multiply(defaultModel.getOtherRatio2());
                //直接经济损失
                BigDecimal directLosses = lifeLosses.add(otherLosses).add(structureDirectLosses).setScale(4, BigDecimal.ROUND_HALF_DOWN);
//                BigDecimal directLosses = structureDirectLosses.add(lifeLosses).add(otherLosses).setScale(4, BigDecimal.ROUND_HALF_DOWN);

                EconomicLossPDCalculation entity = new EconomicLossPDCalculation();

                entity.setAssessId(calculationTasks.getId());
                entity.setAssessCode(calculationTasks.getAssessCode());
                entity.setProvinceName(pcc.getPpName());
                entity.setCityName(pcc.getCityName());
                entity.setCountyName(pcc.getName());
                entity.setCoordinateRange("");
                entity.setGeographyId(extends1);
                entity.setExtends1(extends1);
                entity.setExtreme(key2);
                entity.setHouseDataFlag(calculationTasks.getHouseDataFlag());
                entity.setSeismicInputMode(calculationTasks.getSeismicInputMode());
                entity.setRisk(calculationTasks.getLdPga());
                entity.setGeom(key1);
                entity.setCreateUser(param.get("userId") + "");
                entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());

                entity.setCalculatedValue(String.valueOf(directLosses));
                entity.setCorrectionValue(String.valueOf(directLosses));
//                //概率P(1)计算值
//                BigDecimal calculatedValueP1 = BigDecimal.ZERO;
//                //概率P(1)修正值
//                BigDecimal correctionValueP1 = BigDecimal.ZERO;
//                try{
//                    for (ResistEarthquakesPECalculation peCalculation : resistEarthquakesPECalculations) {
//                        if(org.apache.commons.lang3.StringUtils.isNotBlank(peCalculation.getExtends1())){
//                            if("d831f81a1b79447d9738038625dd5479".equals(extends1)){
//                                System.out.println("111");
//                            }
//                            if (extends1.equals(peCalculation.getExtends1()) && key2.equals(peCalculation.getDamageDegree())) {
//                                calculatedValueP1 = peCalculation.getCorrectionValueP1();
//                                correctionValueP1 = calculatedValueP1;
//                                break;
//                            }
//                        }
//                    }
//                    entity.setCalculatedValueP1(calculatedValueP1.setScale(6, RoundingMode.HALF_UP) + "");
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//                entity.setCorrectionValueP1(correctionValueP1.setScale(6, RoundingMode.HALF_UP) + "");
                entity.setDelFlag("0");
                for (String years : calculationTasks.getYear().split(",")) {
                    EconomicLossPDCalculation entity1 = new EconomicLossPDCalculation();
                    UpdateUtil.copyNullProperties(entity, entity1);
                    entity1.setId(UUIDGenerator.getUUID());
//                    //概率值p(T)(用【概率P(1)修正值】进行计算）
//                    BigDecimal chancePt = correctionValueP1.multiply(new BigDecimal(years)).setScale(6, RoundingMode.HALF_UP);
//                    entity1.setChancePt(chancePt + "");
                   /* //期望值（万元）
                    entity1.setExpectValue(chancePt.multiply(directLosses).setScale(6, RoundingMode.HALF_UP));*/
                    entity1.setYears(years);
                    entity1.setDelFlag("0");
                    //去掉重复数据。
                    if (PlatformObjectUtils.isNotEmpty(list)) {
                        List<EconomicLossPDCalculation> collect = list.stream().filter(entity2 -> entity2.getGeom().equals(entity1.getGeom()) && entity2.getYears().equals(entity1.getYears()) && entity2.getExtreme().equals(entity1.getExtreme())).collect(Collectors.toList());
                        if (PlatformObjectUtils.isNotEmpty(collect)) {
                            if ("0".equals(collect.get(0).getCalculatedValue())) {
                                list.remove(collect.get(0));
                                list.add(entity1);
                                continue;
                            }
                            continue;
                        }
                    }
                    list.add(entity1);
                }
            }
        }
        // //去重问题
        // List<EconomicLossPDCalculation> resultList = new ArrayList<>();
        // if (PlatformObjectUtils.isNotEmpty(list)) {
        //     for (EconomicLossPDCalculation calculation : list) {
        //         List<EconomicLossPDCalculation> collect = list.stream().filter(entity -> entity.getId().equals(calculation.getId())).collect(Collectors.toList());
        //         List<EconomicLossPDCalculation> collect1 = resultList.stream().filter(entity -> entity.getId().equals(collect.get(0).getId())).collect(Collectors.toList());
        //         if (PlatformObjectUtils.isNotEmpty(collect1)) {
        //             continue;
        //         }
        //         resultList.add(collect.get(0));
        //     }
        //
        // }
        economicLossPDRepository.batchCalculation(list);
    }

//    private Map<String, Map<String, String[]>> centerEvaluate3(List<DictEntityVo> structureList, CalculationTasks calculationTasks
//            , EconomicLosses defaultModel, Map<String, Object> param, List<VillageTownHosPeoEntity> list1
//            , List<BuildingResetUnitPriceEntity> list2) throws Exception {
//        String geom = calculationTasks.getCoordinateRange();
//        Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap = null;
//        if ("3".equals(calculationTasks.getSeismicInputMode())) {
//            //发生概率危险性的数据
//            List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList1(calculationTasks.getLdPga(), geom,calculationTasks);
//            if (psHazardDataValueList == null || psHazardDataValueList.size() < 1) {
//                return null;
//            }
//            //转换发生概率危险性的数据的格式
//            stringMapMap = publicOperateService.buildPsHazardDataValue(psHazardDataValueList).rowMap();
//        } else if ("4".equals(calculationTasks.getSeismicInputMode())) {
//            if ("0".equals(calculationTasks.getLdPga())) {
//                //烈度
//                stringMapMap = publicOperateService.transition1(geom, "", "0").rowMap();
//            } else if ("1".equals(calculationTasks.getLdPga())) {
//                //pga
//                stringMapMap = publicOperateService.transition2(geom, "", "0").rowMap();
//            } else {
//                throw new RuntimeException("参数2错误，请联系管理员！");
//            }
//        } else {
//            throw new RuntimeException("参数1错误，请联系管理员！");
//        }
//        /**
//         * key: 一个格网
//         * value: 一个格网的数据
//         * Map<String, String[]>
//         *     key: 破坏程度
//         *     value: 建筑物直接经济损失
//         *
//         */
//        Map<String, Map<String, String[]>> mapMap = new HashMap<>();
//        String province = null, city = null, county = null;
//        //烈度
//        Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx = null;
//        //pga
//        JSONArray pgaOfYsx = null;
//        //人口与建筑物数据
//        VillageTownHosPeoEntity villageTownHosPeoEntity = null;
//        //建筑物结构重置单价
//        BuildingResetUnitPriceEntity buildingPriceEntity = null;
//        //根据省市县和版本查询13张表数据
//        if (structureList.size() > 0) {
////             //数据视图条件
////             QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
////             //写入条件版本号
////             queryByVersionParam.setVersionCode(calculationTasks.getHouseData());
//// //                        //获取区县code
//// //                         //0为省市区县1为地图圈选
////             queryByVersionParam.setGeomType(1);
////             queryByVersionParam.setGeom(calculationTasks.getCoordinateRange());
//            for (DictEntityVo vo : structureList) {
//                // queryByVersionParam.setTypeCode(vo.getDictItemCode());
//                //烈度的公里网格
//                List<Grid13VO> jggwList = calculationTasksRepository.getGlGwDate(calculationTasks.getId(), vo.getDictItemCode());
//                //获取区县信息
//                if(PlatformObjectUtils.isNotEmpty(jggwList)){
//                    Map<String, List<Grid13VO>> districtMap = jggwList.stream().collect(Collectors.groupingBy(grid13VO -> grid13VO.getProvince() + "_" + grid13VO.getCity() + "_" + grid13VO.getCounty()));
//                    districtMap.forEach((k,v)->{
//                        String provinceName = k.split("_")[0];
//                        String cityName = k.split("_")[1];
//                        String countyName = k.split("_")[2];
//                        if ("0".equals(calculationTasks.getLdPga())) {
//                            //烈度
//                            try {
//                                ldOfYsx.set(ysxUtil.getYSX(calculationTasks.getId(), provinceName,cityName, countyName));
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        } else {
//                            //pga
//                            try {
//                                pgaOfYsx = jcsjRestManager.getPgaOfYsx(cityName, cityName, countyName);
//                            } catch (BizException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });
//                }
//                //根据字典值获取不同结构类型的具体数据并计算
//                if (PlatformObjectUtils.isNotEmpty(jggwList) && jggwList.size() > 0) {
//                    //key:破坏程度    value: 建筑物直接经济损失
//                    Map<String, String[]> map = null;
//                    String[] strings = null;
//                    //建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
//                    BigDecimal structureDirectLosses = BigDecimal.ZERO;
//                    if ("0".equals(calculationTasks.getLdPga())) {
//                        //烈度
//                        //一个obj就是一个网格的一个结构类型的数据
//                        for (Grid13VO obj : jggwList) {
//                            // if("3d33788670394fdf9120197f048b9854".equals(obj.getExtends1())){
//                            //     System.out.println();
//                            // }else {
//                            //     continue;
//                            // }
//                            //如果总面积是0,就不用继续进行了
//                            // if (obj.getTotalArea() == null || obj.getTotalArea() == 0.0) {
//                            //     continue;
//                            // }
//                            if (PlatformObjectUtils.isEmpty(obj.getProvince()) || PlatformObjectUtils.isEmpty(obj.getCity()) || PlatformObjectUtils.isEmpty(obj.getCounty())) {
//                                continue;
//                            }
//                            //if (!obj.getProvince().equals(province) || !obj.getCity().equals(city) || !obj.getCounty().equals(county)) {
//                                //人口与建筑物数据
//                                villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCityForName(obj.getProvince(), obj.getCity(), obj.getCounty(), "");
//                                //建筑物结构重置单价
//                                if(PlatformObjectUtils.isEmpty(villageTownHosPeoEntity)){
//                                    continue;
//                                    //throw new RuntimeException("计算未完成，无法获取"+obj.getProvince()+""+obj.getCity()+""+obj.getCounty()+"的人口与建筑物数据");
//                                }
//                                try{
//                                    buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvinceName(obj.getProvince(), obj.getCity(), obj.getCounty());
//                                }catch (Exception e){
//                                    e.printStackTrace();
//                                }
//                                if(PlatformObjectUtils.isEmpty(buildingPriceEntity)){
//                                    continue;
//                                    //throw new RuntimeException("计算未完成，无法获取"+obj.getProvince()+""+obj.getCity()+""+obj.getCounty()+"的建筑物结构重置单价");
//                                }
//                                list1.add(villageTownHosPeoEntity);
//                                list2.add(buildingPriceEntity);
//                                if ("0".equals(calculationTasks.getLdPga())) {
//                                    //烈度
//                                    try {
//                                        ldOfYsx = ysxUtil.getYSX(calculationTasks.getId(), obj.getProvince(),obj.getCity(), obj.getCounty());
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//                                } else {
//                                    //pga
//                                    try {
//                                        pgaOfYsx = jcsjRestManager.getPgaOfYsx(obj.getProvince(),obj.getCity(), obj.getCounty());
//                                    } catch (BizException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            //}
//                            //一个公里网格下的危险性数据，年平均发生概率，key为X轴(im)，value为Y轴(年平均发生概率)
//                            Map<List<String>, List<BigDecimal>> listListMap = stringMapMap.get(obj.getExtends1());
//                            String key1 = obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty() + "-" + obj.getGeom();
//                            if (mapMap.containsKey(key1)) {
//                                map = mapMap.get(key1);
//                            } else {
//                                map = new HashMap<>();
//                            }
//                            //总面积当前坐标总面积
//                            BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
//                            //ysxData的第一个key，结构类型
//                            String mapKey = "";
//                            //获取对应易损性结构类型
//                            if (!"城镇钢混结构".equals(obj.getStructureType())) {
//                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
//                            } else {
//                                //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
//                                if (obj.getF31() > 0) {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
//                                } else if (obj.getF17F30() > 0) {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
//                                } else if (obj.getF11F16() > 0) {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
//                                } else if (obj.getF7F10() > 0) {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
//                                } else {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
//                                }
//                                if ("剪力墙结构".equals(mapKey)) {
//                                    mapKey = "钢筋混凝土结构-" + mapKey;
//                                }
//                            }
//                            //当前结构的易损性数据
//                            Map<String, Map<String, BuildingVulnerability>> sfIntensityMap = ldOfYsx.get().get(mapKey);
//                            //该数据所具备的设防烈度和对应的烈度面积占比结构
//                            Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
//                            //建筑物结构的重置单价
//                            BigDecimal buildingPrice = BigDecimal.ZERO;
//                            if (buildingPriceEntity != null) {
//                                switch (mapKey) {
//                                    case "砌体结构-砖混结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
//                                        break;
//                                    case "钢筋混凝土结构-剪力墙结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
//                                        break;
//                                    case "钢结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
//                                        break;
//                                    case "木结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
//                                        break;
//                                    case "其他":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
//                                        break;
//                                    case "土木结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
//                                        break;
//                                    case "钢筋混凝土结构-框架结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
//                                        break;
//                                    case "钢筋混凝土结构-框架-剪力墙结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
//                                        break;
//                                }
//                            }
//                            //地区室内财产（元/每平米）
//                            BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
//                            if (obj.getStructureType().contains("城镇")) {
//                                dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
//                            } else {
//                                try{
//                                    dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
//                                }catch (Exception e){
//                                    e.printStackTrace();
//                                }
//
//                            }
//                            if (sfIntensityMap == null || sfIntensityMap.size() < 1) {
//                                continue;
//                            }
//                            //数据的各个破坏程度的面积
//                            for (Map.Entry<String, BigDecimal> entry : intensitAreaMap.entrySet()) {
//                                String sfIntensity = entry.getKey();//设防烈度
//                                BigDecimal sfIntensityArea = totalArea.multiply(entry.getValue());//设防烈度对应的面积
//                                //易损性数据下设防烈度对应的数据
//                                Map<String, BuildingVulnerability> vulnerabilityList = null;
//                                try {
//                                    vulnerabilityList = sfIntensityMap.get(sfIntensity);
//                                } catch (NullPointerException e) {
//                                    e.printStackTrace();
//                                }
//                                //4个破坏程度（轻微，中等，严重，倒塌）
//                                for (int j = 1; j < 5; j++) {
//                                    String extreme = null;
//                                    switch (j) {
//                                        case 1:
//                                            extreme = "pgcd2";
//                                            break;
//                                        case 2:
//                                            extreme = "pgcd3";
//                                            break;
//                                        case 3:
//                                            extreme = "pgcd4";
//                                            break;
//                                        case 4:
//                                            extreme = "pgcd5";
//                                    }
//                                    if (map.containsKey(extreme)) {
//                                        strings = map.get(extreme);
//                                    } else {
//                                        strings = new String[]{obj.getExtends1(), BigDecimal.ZERO + ""};
//                                    }
//                                    if (listListMap != null && listListMap.size() > 0) {
//                                        BigDecimal area = BigDecimal.ZERO;
//                                        List<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
//                                        for (List<String> imList : listListMap.keySet()) {
//                                            //遍历烈度
//                                            for (int zz=0;zz<imList.size();zz++) {
//                                                String im = imList.get(zz);
//                                                String realIntensity = getRealIntensity(im);
//                                                BigDecimal imValue = values.get(0).get(zz);
////                                                switch (im) {
////                                                    case "Ⅴ":
////                                                    case "Ⅵ":
////                                                        im = "6";
////                                                        break;
////                                                    case "Ⅶ":
////                                                        im = "7";
////                                                        break;
////                                                    case "Ⅷ":
////                                                        im = "8";
////                                                        break;
////                                                    case "Ⅸ":
////                                                        im = "9";
////                                                        break;
////                                                    case "Ⅹ":
////                                                    case "Ⅺ":
////                                                    case "Ⅻ":
////                                                        im = "10";
////                                                        break;
////                                                }
//                                                if (vulnerabilityList != null && vulnerabilityList.size() >0) {
//                                                BuildingVulnerability buildingVulnerability = vulnerabilityList.get(realIntensity);
//                                                if (buildingVulnerability != null) {
//                                                    switch (j) {
//                                                        case 1:
//                                                            //轻微破坏面积
//                                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSlight()).multiply(imValue).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
//                                                            break;
//                                                        case 2:
//                                                            //中等破坏面积
//                                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getMid()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
//                                                            break;
//                                                        case 3:
//                                                            //严重破坏面积
//                                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSerious()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
//                                                            break;
//                                                        case 4:
//                                                            //损坏面积
//                                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getDestroy()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
//                                                    }
//                                                    break;
//                                                }
//                                                }
//                                            }
//                                        }
//                                        // //多除以100-----------待修改
//                                        // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
//                                        //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
//                                        strings[1] = new BigDecimal(strings[1]).add(getStructureLossess1(obj.getStructureType(),
//                                                area, buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
//                                    }
//                                    map.put(extreme, strings);
//                                    mapMap.put(key1, map);
//                                }
//                            }
//                            province = obj.getProvince();
//                            city = obj.getCity();
//                            county = obj.getCounty();
//                        }
//                    } else {
//                        //pga
//                        for (Grid13VO obj : jggwList) {
//                            // if("3d33788670394fdf9120197f048b9854".equals(obj.getExtends1())){
//                            //     System.out.println();
//                            // }else {
//                            //     continue;
//                            // }
//                            //如果总面积是0,就不用继续进行了
//                            // if (obj.getTotalArea() == null || obj.getTotalArea() == 0.0) {
//                            //     continue;
//                            // }
//                            if (PlatformObjectUtils.isEmpty(obj.getProvince()) || PlatformObjectUtils.isEmpty(obj.getCity()) || PlatformObjectUtils.isEmpty(obj.getCounty())) {
//                                continue;
//                            }
//                            if (!obj.getProvince().equals(province) || !obj.getCity().equals(city) || !obj.getCounty().equals(county)) {
//                                //人口与建筑物数据
//                                villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCityForName(obj.getProvince(), obj.getCity(), obj.getCounty(), "");
//                                //建筑物结构重置单价
//                                buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvinceName(obj.getProvince(), obj.getCity(), obj.getCounty());
//                                list1.add(villageTownHosPeoEntity);
//                                list2.add(buildingPriceEntity);
//                                if ("1".equals(calculationTasks.getLdPga())) {
//                                    //烈度
//                                    ldOfYsx.set(ysxUtil.getYSX(calculationTasks.getId(), obj.getProvince(), obj.getCity(), obj.getCounty()));
//                                } else {
//                                    //pga
//                                    pgaOfYsx = jcsjRestManager.getPgaOfYsx(obj.getProvince(), obj.getCity(), obj.getCounty());
//                                }
//                            }
//
//                            Map<List<String>, List<BigDecimal>> listListMap = stringMapMap.get(obj.getExtends1());
//                            if (mapMap.containsKey(obj.getGeom())) {
//                                map = mapMap.get(obj.getGeom());
//                            } else {
//                                map = new HashMap<>();
//                            }
//                            //总面积当前坐标总面积
//                            BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
//                            //ysxData的第一个key，结构类型
//                            String mapKey = "";
//                            //获取对应易损性结构类型
//                            if (!"城镇钢混结构".equals(obj.getStructureType())) {
//                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
//                            } else {
//                                //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
//                                if (obj.getF31() > 0) {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
//                                } else if (obj.getF17F30() > 0) {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
//                                } else if (obj.getF11F16() > 0) {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
//                                } else if (obj.getF7F10() > 0) {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
//                                } else {
//                                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
//                                }
//                                if ("剪力墙结构".equals(mapKey)) {
//                                    mapKey = "钢筋混凝土结构-" + mapKey;
//                                }
//                            }
//                            //该数据所具备的设防烈度和对应的烈度面积占比结构
//                            Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
//                            //建筑物结构的重置单价
//                            BigDecimal buildingPrice = BigDecimal.ZERO;
//                            if (buildingPriceEntity != null) {
//                                switch (mapKey) {
//                                    case "砌体结构-砖混结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
//                                        break;
//                                    case "钢筋混凝土结构-剪力墙结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
//                                        break;
//                                    case "钢结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
//                                        break;
//                                    case "木结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
//                                        break;
//                                    case "其他":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
//                                        break;
//                                    case "土木结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
//                                        break;
//                                    case "钢筋混凝土结构-框架结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
//                                        break;
//                                    case "钢筋混凝土结构-框架-剪力墙结构":
//                                        buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
//                                                BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
//                                        break;
//                                }
//                            }
//                            //地区室内财产（元/每平米）
//                            BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
//                            if (obj.getStructureType().contains("城镇")) {
//                                dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
//                            } else {
//                                dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
//                            }
//                            //数据的各个破坏程度的面积
//                            for (Map.Entry<String, BigDecimal> entry : intensitAreaMap.entrySet()) {
//                                String sfIntensity = entry.getKey();//设防烈度
//                                BigDecimal sfIntensityArea = totalArea.multiply(entry.getValue());//设防烈度对应的面积
//                                JSONArray jsonArray = null;
//                                String[] split = mapKey.split("-");
//                                if (split.length == 2) {
//                                    for (int i = 0; i < pgaOfYsx.size(); i++) {
//                                        JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
//                                        if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("structureType1").equals(split[1])
//                                                && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
//                                            jsonArray = jsonObject.getJSONArray("valueList");
//                                            break;
//                                        }
//                                    }
//                                } else {
//                                    for (int i = 0; i < pgaOfYsx.size(); i++) {
//                                        JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
//                                        if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
//                                            jsonArray = jsonObject.getJSONArray("valueList");
//                                            break;
//                                        }
//                                    }
//                                }
//                                if (jsonArray == null) {
//                                    continue;
//                                }
//                                //4个破坏程度（轻微，中等，严重，倒塌）
//                                for (int j = 1; j < 5; j++) {
//                                    JSONObject jsonObject = null;
//                                    String extreme = null;
//                                    String extreme1 = null;
//                                    switch (j) {
//                                        case 1:
//                                            extreme = "pgcd2";
//                                            extreme1 = "轻微破坏";
//                                            break;
//                                        case 2:
//                                            extreme = "pgcd3";
//                                            extreme1 = "中等破坏";
//                                            break;
//                                        case 3:
//                                            extreme = "pgcd4";
//                                            extreme1 = "严重破坏";
//                                            break;
//                                        case 4:
//                                            extreme = "pgcd5";
//                                            extreme1 = "倒塌";
//                                    }
//                                    if (map.containsKey(extreme)) {
//                                        strings = map.get(extreme);
//                                    } else {
//                                        strings = new String[]{obj.getExtends1(), BigDecimal.ZERO + ""};
//                                    }
//                                    for (int i = 0; i < jsonArray.size(); i++) {
//                                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//                                        if (jsonObject1.getString("destructiveState").equals(extreme1)) {
//                                            jsonObject = jsonObject1;
//                                            break;
//                                        }
//                                    }
//                                    if (jsonObject != null) {
//                                        if (listListMap != null && listListMap.size() > 0) {
//                                            BigDecimal area = BigDecimal.ZERO;
//                                            List<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
//                                            for (List<String> imList : listListMap.keySet()) {
//                                                for (int zz=0;zz<imList.size();zz++) {
//                                                    String im = imList.get(zz);
//                                                    BigDecimal imValue = values.get(0).get(zz);
//                                                    BigDecimal funtionValue = publicOperateService.getFuntionValue(jsonObject, im);
//                                                    area = area.add(sfIntensityArea.multiply(funtionValue).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
//                                                }
//                                            }
//                                            // // 多除以100-----------待修改
//                                            // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
//                                            //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
//                                            strings[1] = new BigDecimal(strings[1]).add(getStructureLossess1(obj.getStructureType(),
//                                                    area, buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
//                                        }
//                                    }
//                                    map.put(extreme, strings);
//                                    mapMap.put(obj.getGeom(), map);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        return mapMap;
//    }
private Map<String, Map<String, String[]>> centerEvaluate3(List<DictEntityVo> structureList, CalculationTasks calculationTasks
        , EconomicLosses defaultModel, Map<String, Object> param, List<VillageTownHosPeoEntity> list1
        , List<BuildingResetUnitPriceEntity> list2) throws Exception {
    String geom = calculationTasks.getCoordinateRange();
    Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap = null;
    if ("3".equals(calculationTasks.getSeismicInputMode())) {
        //发生概率危险性的数据
        List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList1(calculationTasks.getLdPga(), geom,calculationTasks);
        if (psHazardDataValueList == null || psHazardDataValueList.size() < 1) {
            return null;
        }
        //转换发生概率危险性的数据的格式
        stringMapMap = publicOperateService.buildPsHazardDataValue(psHazardDataValueList).rowMap();
    } else if ("4".equals(calculationTasks.getSeismicInputMode())) {
        if ("0".equals(calculationTasks.getLdPga())) {
            //烈度
            stringMapMap = publicOperateService.transition1(geom, "", "0").rowMap();
        } else if ("1".equals(calculationTasks.getLdPga())) {
            //pga
            stringMapMap = publicOperateService.transition2(geom, "", "0").rowMap();
        } else {
            throw new RuntimeException("参数2错误，请联系管理员！");
        }
    } else {
        throw new RuntimeException("参数1错误，请联系管理员！");
    }
    /**
     * key: 一个格网
     * value: 一个格网的数据
     * Map<String, String[]>
     *     key: 破坏程度
     *     value: 建筑物直接经济损失
     *
     */
    Map<String, Map<String, String[]>> mapMap = new HashMap<>();
    String province = null, city = null, county = null;
    //烈度
    AtomicReference<Map<String, Map<String, Map<String, BuildingVulnerability>>>> ldOfYsx = null;
    //pga
    AtomicReference<JSONArray> pgaOfYsx = null;
    //人口与建筑物数据
    VillageTownHosPeoEntity villageTownHosPeoEntity = null;
    //建筑物结构重置单价
    BuildingResetUnitPriceEntity buildingPriceEntity = null;
    //根据省市县和版本查询13张表数据
    if (structureList.size() > 0) {
        for (DictEntityVo vo : structureList) {
            // queryByVersionParam.setTypeCode(vo.getDictItemCode());
            //烈度的公里网格
            List<Grid13VO> jggwList = calculationTasksRepository.getGlGwDate(calculationTasks.getId(), vo.getDictItemCode());
            //获取区县信息
            if(PlatformObjectUtils.isNotEmpty(jggwList)){
                Map<String, List<Grid13VO>> districtMap = jggwList.stream().collect(Collectors.groupingBy(grid13VO -> grid13VO.getProvince() + "_" + grid13VO.getCity() + "_" + grid13VO.getCounty()));
                districtMap.forEach((k,v)->{
                    String provinceName = k.split("_")[0];
                    String cityName = k.split("_")[1];
                    String countyName = k.split("_")[2];
                    if ("0".equals(calculationTasks.getLdPga())) {
                        //烈度
                        try {
                            ldOfYsx.set(ysxUtil.getYSX(calculationTasks.getId(), provinceName, cityName, countyName));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        //pga
                        try {
                            pgaOfYsx.set(jcsjRestManager.getPgaOfYsx(cityName, cityName, countyName));
                        } catch (BizException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            //根据字典值获取不同结构类型的具体数据并计算
            if (PlatformObjectUtils.isNotEmpty(jggwList) && jggwList.size() > 0) {
                //key:破坏程度    value: 建筑物直接经济损失
                Map<String, String[]> map = null;
                String[] strings = null;
                if ("0".equals(calculationTasks.getLdPga())) {
                    //烈度
                    //一个obj就是一个网格的一个结构类型的数据
                    for (Grid13VO obj : jggwList) {
                        if (PlatformObjectUtils.isEmpty(obj.getProvince()) || PlatformObjectUtils.isEmpty(obj.getCity()) || PlatformObjectUtils.isEmpty(obj.getCounty())) {
                            continue;
                        }

                        //人口与建筑物数据
                        villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCityForName(obj.getProvince(), obj.getCity(), obj.getCounty(), "");
                        if(PlatformObjectUtils.isEmpty(villageTownHosPeoEntity)){
//                            continue;
                            throw new Exception("该区域内"+obj.getProvince()+obj.getCity()+obj.getCounty()+"的人口与建筑物数据未设置");
                        }
                        //建筑物结构重置单价
                        try{
                            buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvinceName(obj.getProvince(), obj.getCity(), obj.getCounty());
                        }catch (Exception e){
                            throw new Exception("该区域内"+obj.getProvince()+obj.getCity()+obj.getCounty()+"的建筑物结构重置单价未设置");
                        }
                        if(PlatformObjectUtils.isEmpty(buildingPriceEntity)){
                            //continue;
                            throw new Exception("该区域内"+obj.getProvince()+obj.getCity()+obj.getCounty()+"的建筑物结构重置单价未设置");
                        }
                        list1.add(villageTownHosPeoEntity);
                        list2.add(buildingPriceEntity);
                        //}
                        //一个公里网格下的危险性数据，年平均发生概率，key为X轴(im)，value为Y轴(年平均发生概率)
                        Map<List<String>, List<BigDecimal>> listListMap = stringMapMap.get(obj.getExtends1());
                        String key1 = obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty() + "-" + obj.getGeom();
                        if (mapMap.containsKey(key1)) {
                            map = mapMap.get(key1);
                        } else {
                            map = new HashMap<>();
                        }
                        //总面积当前坐标总面积
                        BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
                        //ysxData的第一个key，结构类型
                        String mapKey = "";
                        //获取对应易损性结构类型
                        if (!"城镇钢混结构".equals(obj.getStructureType())) {
                            mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
                        } else {
                            //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
                            if (obj.getF31() > 0) {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                            } else if (obj.getF17F30() > 0) {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                            } else if (obj.getF11F16() > 0) {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                            } else if (obj.getF7F10() > 0) {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                            } else {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
                            }
                            if ("剪力墙结构".equals(mapKey)) {
                                mapKey = "钢筋混凝土结构-" + mapKey;
                            }
                        }
                        //当前结构的易损性数据
                        Map<String, Map<String, BuildingVulnerability>> sfIntensityMap = ldOfYsx.get().get(mapKey);
                        //该数据所具备的设防烈度和对应的烈度面积占比结构
                        Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
                        //建筑物结构的重置单价
                        BigDecimal buildingPrice = BigDecimal.ZERO;
                        if (buildingPriceEntity != null) {
                            switch (mapKey) {
                                case "砌体结构-砖混结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
                                    break;
                                case "钢筋混凝土结构-剪力墙结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
                                    break;
                                case "钢结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
                                    break;
                                case "木结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
                                    break;
                                case "其他":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
                                    break;
                                case "土木结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
                                    break;
                                case "钢筋混凝土结构-框架结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
                                    break;
                                case "钢筋混凝土结构-框架-剪力墙结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
                                    break;
                            }
                        }
                        //地区室内财产（元/每平米）
                        BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
                        if (obj.getStructureType().contains("城镇")) {
                            dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
                        } else {
                            try{
                                dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }
                        if (sfIntensityMap == null || sfIntensityMap.size() < 1) {
                            continue;
                        }
                        //数据的各个破坏程度的面积
                        for (Map.Entry<String, BigDecimal> entry : intensitAreaMap.entrySet()) {
                            String sfIntensity = entry.getKey();//设防烈度
                            BigDecimal sfIntensityArea = totalArea.multiply(entry.getValue());//设防烈度对应的面积
                            //易损性数据下设防烈度对应的数据
                            Map<String, BuildingVulnerability> vulnerabilityList = null;
                            try {
                                vulnerabilityList = sfIntensityMap.get(sfIntensity);
                            } catch (NullPointerException e) {
                                e.printStackTrace();
                            }
                            //4个破坏程度（轻微，中等，严重，倒塌）
                            for (int j = 1; j < 5; j++) {
                                String extreme = null;
                                switch (j) {
                                    case 1:
                                        extreme = "pgcd2";
                                        break;
                                    case 2:
                                        extreme = "pgcd3";
                                        break;
                                    case 3:
                                        extreme = "pgcd4";
                                        break;
                                    case 4:
                                        extreme = "pgcd5";
                                }
                                if (map.containsKey(extreme)) {
                                    strings = map.get(extreme);
                                } else {
                                    strings = new String[]{obj.getExtends1(), BigDecimal.ZERO + ""};
                                }
                                if (listListMap != null && listListMap.size() > 0) {
                                    BigDecimal area = BigDecimal.ZERO;
                                    List<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
                                    for (List<String> imList : listListMap.keySet()) {
                                        //遍历烈度
                                        for (int zz=0;zz<imList.size();zz++) {
                                            String im = imList.get(zz);
                                            String realIntensity = getRealIntensity(im);
                                            BigDecimal imValue = values.get(0).get(zz);
                                            if (vulnerabilityList != null && vulnerabilityList.size() >0) {
                                                BuildingVulnerability buildingVulnerability = vulnerabilityList.get(realIntensity);
                                                if (buildingVulnerability != null) {
                                                    switch (j) {
                                                        case 1:
                                                            //轻微破坏面积
                                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSlight()).multiply(imValue).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                            break;
                                                        case 2:
                                                            //中等破坏面积
                                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getMid()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                            break;
                                                        case 3:
                                                            //严重破坏面积
                                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSerious()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                            break;
                                                        case 4:
                                                            //损坏面积
                                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getDestroy()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    // //多除以100-----------待修改
                                    // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                                    //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
                                    strings[1] = new BigDecimal(strings[1]).add(getStructureLossess1(obj.getStructureType(),
                                            area, buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
                                }
                                map.put(extreme, strings);
                                mapMap.put(key1, map);
                            }
                        }
                        province = obj.getProvince();
                        city = obj.getCity();
                        county = obj.getCounty();
                    }
                } else {
                    //pga
                    for (Grid13VO obj : jggwList) {
                        // if("3d33788670394fdf9120197f048b9854".equals(obj.getExtends1())){
                        //     System.out.println();
                        // }else {
                        //     continue;
                        // }
                        //如果总面积是0,就不用继续进行了
                        // if (obj.getTotalArea() == null || obj.getTotalArea() == 0.0) {
                        //     continue;
                        // }
                        if (PlatformObjectUtils.isEmpty(obj.getProvince()) || PlatformObjectUtils.isEmpty(obj.getCity()) || PlatformObjectUtils.isEmpty(obj.getCounty())) {
                            continue;
                        }
                        if (!obj.getProvince().equals(province) || !obj.getCity().equals(city) || !obj.getCounty().equals(county)) {
                            //人口与建筑物数据
                            villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCityForName(obj.getProvince(), obj.getCity(), obj.getCounty(), "");
                            if(villageTownHosPeoEntity == null){
                                throw new Exception("该区域内"+obj.getProvince()+obj.getCity()+obj.getCounty()+"的人口与建筑物数据未设置");
                            }
                            //建筑物结构重置单价
                            buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvinceName(obj.getProvince(), obj.getCity(), obj.getCounty());
                            if(buildingPriceEntity == null){
                                throw new Exception("该区域内"+obj.getProvince()+obj.getCity()+obj.getCounty()+"的建筑物结构重置单价未设置");
                            }
                            list1.add(villageTownHosPeoEntity);
                            list2.add(buildingPriceEntity);
                            if ("1".equals(calculationTasks.getLdPga())) {
                                //烈度
                                ldOfYsx.set(ysxUtil.getYSX(calculationTasks.getId(), obj.getProvince(), obj.getCity(), obj.getCounty()));
                            } else {
                                //pga
                                pgaOfYsx.set(jcsjRestManager.getPgaOfYsx(obj.getProvince(), obj.getCity(), obj.getCounty()));
                            }
                        }

                        Map<List<String>, List<BigDecimal>> listListMap = stringMapMap.get(obj.getExtends1());
                        if (mapMap.containsKey(obj.getGeom())) {
                            map = mapMap.get(obj.getGeom());
                        } else {
                            map = new HashMap<>();
                        }
                        //总面积当前坐标总面积
                        BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
                        //ysxData的第一个key，结构类型
                        String mapKey = "";
                        //获取对应易损性结构类型
                        if (!"城镇钢混结构".equals(obj.getStructureType())) {
                            mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
                        } else {
                            //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
                            if (obj.getF31() > 0) {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                            } else if (obj.getF17F30() > 0) {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                            } else if (obj.getF11F16() > 0) {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                            } else if (obj.getF7F10() > 0) {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                            } else {
                                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
                            }
                            if ("剪力墙结构".equals(mapKey)) {
                                mapKey = "钢筋混凝土结构-" + mapKey;
                            }
                        }
                        //该数据所具备的设防烈度和对应的烈度面积占比结构
                        Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
                        //建筑物结构的重置单价
                        BigDecimal buildingPrice = BigDecimal.ZERO;
                        if (buildingPriceEntity != null) {
                            switch (mapKey) {
                                case "砌体结构-砖混结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
                                    break;
                                case "钢筋混凝土结构-剪力墙结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
                                    break;
                                case "钢结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
                                    break;
                                case "木结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
                                    break;
                                case "其他":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
                                    break;
                                case "土木结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
                                    break;
                                case "钢筋混凝土结构-框架结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
                                    break;
                                case "钢筋混凝土结构-框架-剪力墙结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
                                    break;
                            }
                        }
                        //地区室内财产（元/每平米）
                        BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
                        if (obj.getStructureType().contains("城镇")) {
                            dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
                        } else {
                            dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
                        }
                        //数据的各个破坏程度的面积
                        for (Map.Entry<String, BigDecimal> entry : intensitAreaMap.entrySet()) {
                            String sfIntensity = entry.getKey();//设防烈度
                            BigDecimal sfIntensityArea = totalArea.multiply(entry.getValue());//设防烈度对应的面积
                            JSONArray jsonArray = null;
                            String[] split = mapKey.split("-");
                            if (split.length == 2) {
                                for (int i = 0; i < pgaOfYsx.get().size(); i++) {
                                    JSONObject jsonObject = pgaOfYsx.get().getJSONObject(i);
                                    if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("structureType1").equals(split[1])
                                            && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
                                        jsonArray = jsonObject.getJSONArray("valueList");
                                        break;
                                    }
                                }
                            } else {
                                for (int i = 0; i < pgaOfYsx.get().size(); i++) {
                                    JSONObject jsonObject = pgaOfYsx.get().getJSONObject(i);
                                    if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
                                        jsonArray = jsonObject.getJSONArray("valueList");
                                        break;
                                    }
                                }
                            }
                            if (jsonArray == null) {
                                continue;
                            }
                            //4个破坏程度（轻微，中等，严重，倒塌）
                            for (int j = 1; j < 5; j++) {
                                JSONObject jsonObject = null;
                                String extreme = null;
                                String extreme1 = null;
                                switch (j) {
                                    case 1:
                                        extreme = "pgcd2";
                                        extreme1 = "轻微破坏";
                                        break;
                                    case 2:
                                        extreme = "pgcd3";
                                        extreme1 = "中等破坏";
                                        break;
                                    case 3:
                                        extreme = "pgcd4";
                                        extreme1 = "严重破坏";
                                        break;
                                    case 4:
                                        extreme = "pgcd5";
                                        extreme1 = "倒塌";
                                }
                                if (map.containsKey(extreme)) {
                                    strings = map.get(extreme);
                                } else {
                                    strings = new String[]{obj.getExtends1(), BigDecimal.ZERO + ""};
                                }
                                for (int i = 0; i < jsonArray.size(); i++) {
                                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                                    if (jsonObject1.getString("destructiveState").equals(extreme1)) {
                                        jsonObject = jsonObject1;
                                        break;
                                    }
                                }
                                if (jsonObject != null) {
                                    if (listListMap != null && listListMap.size() > 0) {
                                        BigDecimal area = BigDecimal.ZERO;
                                        for (List<String> imList : listListMap.keySet()) {
                                            for (int zz=0;zz<imList.size();zz++) {
                                                String im = imList.get(zz);
                                                BigDecimal funtionValue = publicOperateService.getFuntionValue(jsonObject, im);
                                                area = area.add(sfIntensityArea.multiply(funtionValue));
                                            }
                                        }
                                        strings[1] = new BigDecimal(strings[1]).add(getStructureLossess1(obj.getStructureType(),
                                                area, buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
                                    }
                                }
                                map.put(extreme, strings);
                                mapMap.put(obj.getGeom(), map);
                            }
                        }
                    }
                }
            }
        }
    }
    return mapMap;
}

    private void getInitResultData2(Map<String, Map<String, String[]>> mapMap, EconomicLosses defaultModel, CalculationTasks calculationTasks
            , Map<String, Object> param, List<ResistEarthquakesPECalculation> resistEarthquakesPECalculations) {
        List<EconomicLossPDCalculation> list = new ArrayList<>();
        for (Map.Entry<String, Map<String, String[]>> entry1 : mapMap.entrySet()) {
            String[] key1 = entry1.getKey().split("-");
            for (Map.Entry<String, String[]> entry2 : entry1.getValue().entrySet()) {
                String key2 = entry2.getKey();//破坏程度
                String extends1 = entry2.getValue()[0];
                BigDecimal structureDirectLosses = new BigDecimal(entry2.getValue()[1]);//建筑物直接经济损失
                //生命线经济损失评估
                BigDecimal lifeLosses = structureDirectLosses.divide(defaultModel.getLifeRatio1(), 4, BigDecimal.ROUND_DOWN).multiply(defaultModel.getLifeRatio2());
                //其他经济损失评估
                BigDecimal otherLosses = structureDirectLosses.divide(defaultModel.getOtherRatio1(), 4, BigDecimal.ROUND_DOWN).multiply(defaultModel.getOtherRatio2());
                //直接经济损失
                BigDecimal directLosses = structureDirectLosses.add(lifeLosses).add(otherLosses).setScale(4, BigDecimal.ROUND_HALF_DOWN);

                EconomicLossPDCalculation entity = new EconomicLossPDCalculation();
                entity.setId(UUIDGenerator.getUUID());
                entity.setAssessId(calculationTasks.getId());
                entity.setAssessCode(calculationTasks.getAssessCode());
                entity.setProvinceName(key1[0]);
                entity.setCityName(key1[1]);
                entity.setCountyName(key1[2]);
                entity.setCoordinateRange(key1[3]);
                entity.setGeographyId(extends1);
                entity.setExtends1(extends1);
                entity.setExtreme(key2);
                entity.setHouseDataFlag(calculationTasks.getHouseDataFlag());
                entity.setSeismicInputMode(calculationTasks.getSeismicInputMode());
                entity.setRisk(calculationTasks.getLdPga());
                entity.setGeom(key1[3]);
                entity.setCreateUser(param.get("userId") + "");
                entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());

                entity.setCalculatedValue(String.valueOf(directLosses));
                entity.setCorrectionValue(String.valueOf(directLosses));
                //概率P(1)计算值
                BigDecimal calculatedValueP1 = BigDecimal.ZERO;
                //概率P(1)修正值
                BigDecimal correctionValueP1 = BigDecimal.ZERO;
                for (ResistEarthquakesPECalculation peCalculation : resistEarthquakesPECalculations) {
                    if (extends1.equals(peCalculation.getExtends1()) && key2.equals(peCalculation.getDamageDegree())) {
                        calculatedValueP1 = peCalculation.getCorrectionValueP1();
                        correctionValueP1 = calculatedValueP1;
                        break;
                    }
                }
//                entity.setCalculatedValueP1(calculatedValueP1 + "");
//                entity.setCorrectionValueP1(correctionValueP1 + "");
                for (String years : calculationTasks.getYear().split(",")) {
                    EconomicLossPDCalculation entity1 = new EconomicLossPDCalculation();
                    UpdateUtil.copyNullProperties(entity, entity1);
//                    //概率值p(T)(用【概率P(1)修正值】进行计算）
//                    BigDecimal chancePt = correctionValueP1.multiply(new BigDecimal(years));
//                    entity1.setChancePt(chancePt + "");
//                    //期望值（万元）
//                    entity1.setExpectValue(chancePt.multiply(directLosses));
                    entity1.setYears(years);
                    entity1.setDelFlag("0");
                    list.add(entity1);
                }
            }
        }
        economicLossPDRepository.batchCalculation(list);
    }

    private Map<String, Map<String, String[]>> centerEvaluate2(PCC pcc, CalculationTasks calculationTasks
            , EconomicLosses defaultModel, Map<String, Object> param, List<VillageTownHosPeoEntity> list1
            , List<BuildingResetUnitPriceEntity> list2) throws Exception {
        handleDistirct(pcc);
        //人口与建筑物数据
        VillageTownHosPeoEntity villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCity(pcc.getPpName(), pcc.getCityName(), pcc.getName(), "");
        if (PlatformObjectUtils.isEmpty(villageTownHosPeoEntity)) {
            throw new Exception("该区域内"+pcc.getPpName()+pcc.getCityName()+pcc.getName()+"的人口与建筑物数据未设置");
        }
        //建筑物结构重置单价
        BuildingResetUnitPriceEntity buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvince(pcc.getPid(), pcc.getCid(), pcc.getId());
        if (PlatformObjectUtils.isEmpty(buildingPriceEntity)) {
            throw new Exception("该区域内"+pcc.getPpName()+pcc.getCityName()+pcc.getName()+"的建筑物结构重置单价未设置");
        }
        list1.add(villageTownHosPeoEntity);
        list2.add(buildingPriceEntity);
        if ("0".equals(calculationTasks.getLdPga())) {
            //烈度
            Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx =
                    ysxUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
            param.put("ldOfYsx", ldOfYsx);
        } else {
            //pga
            JSONArray pgaOfYsx = jcsjRestManager.getPgaOfYsx(pcc.getPpName(), pcc.getCityName(), pcc.getName());
            param.put("pgaOfYsx", pgaOfYsx);
        }
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        String divisionIds = null;
        try {
            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(pcc.getPpName(), "UTF-8"),
                    URLEncoder.encode(pcc.getCityName(), "UTF-8"), URLEncoder.encode(pcc.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (divisionIds == null) {
            return null;
        }
        String code = null;
        if (areaIdCodeMap == null || areaIdCodeMap.size() < 1) {
            code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
        } else {
            code = areaIdCodeMap.get(divisionIds.split("_")[2]);
        }
        String geom = jcsjRestManager.getGeomByCode(code, "3");
        Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap = null;
        if ("3".equals(calculationTasks.getSeismicInputMode())) {
            //发生概率危险性的数据
            List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList1(calculationTasks.getLdPga(), geom,calculationTasks);
            if (psHazardDataValueList == null || psHazardDataValueList.size() < 1) {
                return null;
            }
            //转换发生概率危险性的数据的格式
            stringMapMap = publicOperateService.buildPsHazardDataValue(psHazardDataValueList).rowMap();
        } else if ("4".equals(calculationTasks.getSeismicInputMode())) {
            if ("0".equals(calculationTasks.getLdPga())) {
                //烈度
                stringMapMap = publicOperateService.transition1(geom, "", "1").rowMap();
            } else if ("1".equals(calculationTasks.getLdPga())) {
                //pga
                stringMapMap = publicOperateService.transition2(geom, "", "1").rowMap();
            } else {
                throw new RuntimeException("参数2错误，请联系管理员！");
            }
        } else {
            throw new RuntimeException("参数1错误，请联系管理员！");
        }
        /**
         * key: 一个格网
         * value: 一个格网的数据
         * Map<String, String[]>
         *     key: 破坏程度
         *     value: 建筑物直接经济损失
         *
         */
        Map<String, Map<String, String[]>> mapMap = new HashMap<>();
//         //数据视图条件
//         QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
//         //写入条件版本号
//         queryByVersionParam.setVersionCode(calculationTasks.getHouseData());
// //                        //获取区县code
// //                         //0为省市区县1为地图圈选
//         queryByVersionParam.setGeomType(0);
//         queryByVersionParam.setProvince(pcc.getPpName());
//         queryByVersionParam.setCity(pcc.getCityName());
//         queryByVersionParam.setCounty(pcc.getName());
        //房屋单体数据
        List<BuildingIndividualEntity> jggwList = calculationTasksRepository.getMonomerDate(calculationTasks.getId());
        Map<String, List<BuildingIndividualEntity>> jggwMap = initList1(jggwList);
        //根据字典值获取不同结构类型的具体数据并计算
        if (PlatformObjectUtils.isNotEmpty(jggwList) && jggwList.size() > 0) {
            if ("1".equals(calculationTasks.getLdPga())) {
                //烈度
                getYwData2OfLd(jggwMap, villageTownHosPeoEntity, buildingPriceEntity,
                        defaultModel, stringMapMap, mapMap, param);
            } else {
                //pga
                getYwData2OfPga(jggwMap, villageTownHosPeoEntity, buildingPriceEntity,
                        defaultModel, stringMapMap, mapMap, param);
            }
        }
        return mapMap;
    }

    private void getYwData2OfLd(Map<String, List<BuildingIndividualEntity>> jggwMap, VillageTownHosPeoEntity villageTownHosPeoEntity
            , BuildingResetUnitPriceEntity buildingPriceEntity, EconomicLosses defaultModel, Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap
            , Map<String, Map<String, String[]>> mapMap, Map<String, Object> param) {
        //key:（Ⅵ，Ⅶ，Ⅷ，Ⅸ，Ⅹ）
        Map<String, String[]> map = null;
        String[] strings = null;
        //易损性数据
        Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx = (Map<String, Map<String, Map<String, BuildingVulnerability>>>) param.get("ldOfYsx");
        Map<Object, Object> dictItemMap = redisTemplate.opsForHash().entries(FxfzConstants.CACHE_SYS_KEY + "dictItemMap");
        if (dictItemMap.size() < 1) {
            dictItemService.getDictItemMap();
            dictItemMap = redisTemplate.opsForHash().entries(FxfzConstants.CACHE_SYS_KEY + "dictItemMap");
        }
        //建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
        BigDecimal structureDirectLosses = BigDecimal.ZERO;
        //一个obj就是一个网格的一个结构类型的数据
        for (Map.Entry<String, List<BuildingIndividualEntity>> entries1 : jggwMap.entrySet()) {
            String key = entries1.getKey();
            if (mapMap.containsKey(key)) {
                map = mapMap.get(key);
            } else {
                map = new HashMap<>();
            }
            for (BuildingIndividualEntity obj : entries1.getValue()) {
                // if("3d33788670394fdf9120197f048b9854".equals(obj.getExtends1())){
                //     System.out.println();
                // }else {
                //     continue;
                // }
                //如果总面积是0,就不用继续进行了
                // if (obj.getTotalArea() == null || obj.getTotalArea() == 0.0) {
                //     continue;
                // }
                //一个公里网格下的危险性数据，年平均发生概率，key为X轴(im)，value为Y轴(年平均发生概率)
                Map<List<String>, List<BigDecimal>> listListMap = null;
                for (String key1 : stringMapMap.keySet()) {
                    //---------待完成；危险性数据和单体数据相关联
                    if (economicLossEDRepository.getSTIntersects(key1, BigDecimal.valueOf(obj.getLongitude()),
                            BigDecimal.valueOf(obj.getLatitude()))) {
                        listListMap = stringMapMap.get(key1);
                        break;
                    }
                }
                //总面积当前坐标总面积
                // BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
                //ysxData的第一个key，结构类型
                String mapKey = dictItemMap.get("100002-" + obj.getStructureType1()) + "";
                if (PlatformObjectUtils.isNotEmpty(obj.getStructureType2())) {
                    switch (obj.getStructureType1()) {
                        case "1":
                            mapKey = mapKey + "-" + dictItemMap.get("100003-" + obj.getStructureType2()) + "";
                            break;
                        case "2":
                            mapKey = mapKey + "-" + dictItemMap.get("100004-" + obj.getStructureType2()) + "";
                            break;
                        case "6":
                            mapKey = mapKey + "-" + dictItemMap.get("100005-" + obj.getStructureType2()) + "";
                            break;
                        default:
                            mapKey = mapKey + "-" + dictItemMap.get(obj.getStructureType2()) + "";
                    }
                }
                //当前结构的易损性数据
                Map<String, Map<String, BuildingVulnerability>> sfIntensityMap = ldOfYsx.get(mapKey);
                if (sfIntensityMap == null || sfIntensityMap.size() < 1) {
                    continue;
                }
                //该数据所具备的设防烈度和对应的烈度面积占比结构
                String sfIntensity = dictItemMap.get("100001-" + obj.getDefenceLevel()) + "";//设防烈度
                BigDecimal sfIntensityArea = new BigDecimal(obj.getArea());//设防烈度对应的面积
                //建筑物结构的重置单价
                BigDecimal buildingPrice = BigDecimal.ZERO;
                if (buildingPriceEntity != null) {
                    switch (mapKey) {
                        case "砌体结构-砖混结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
                            break;
                        case "钢筋混凝土结构-剪力墙结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
                            break;
                        case "钢结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
                            break;
                        case "木结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
                            break;
                        case "其他":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
                            break;
                        case "土木结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
                            break;
                        case "钢筋混凝土结构-框架结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
                            break;
                        case "钢筋混凝土结构-框架-剪力墙结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
                            break;
                    }
                }
                //地区室内财产（元/每平米）
                BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
                if ("1".equals(obj.getTownorcontry())) {
                    dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
                } else {
                    dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
                }
                //易损性数据下设防烈度对应的数据
                Map<String, BuildingVulnerability> vulnerabilityList = null;
                try {
                    vulnerabilityList = sfIntensityMap.get(sfIntensity);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                //4个破坏程度（轻微，中等，严重，倒塌）
                for (int j = 1; j < 5; j++) {
                    String extreme = null;
                    switch (j) {
                        case 1:
                            extreme = "pgcd2";
                            break;
                        case 2:
                            extreme = "pgcd3";
                            break;
                        case 3:
                            extreme = "pgcd4";
                            break;
                        case 4:
                            extreme = "pgcd5";
                    }
                    if (map.containsKey(extreme)) {
                        strings = map.get(extreme);
                    } else {
                        strings = new String[]{obj.getBuildingCode(), BigDecimal.ZERO + ""};
                    }
                    if (listListMap != null && listListMap.size() > 0) {
                        BigDecimal area = BigDecimal.ZERO;
                        List<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
                        for (List<String> imList : listListMap.keySet()) {
                            //遍历烈度
                            for (int zz=0;zz<imList.size();zz++) {
                                String im = imList.get(zz);
                                BigDecimal imValue = values.get(0).get(zz);
                                String realIntensity = getRealIntensity(im);
                                if (vulnerabilityList != null && vulnerabilityList.size() >0) {
                                BuildingVulnerability buildingVulnerability = vulnerabilityList.get(realIntensity);
                                if (buildingVulnerability != null) {
                                    switch (j) {
                                        case 1:
                                            //轻微破坏面积
                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSlight()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                            break;
                                        case 2:
                                            //中等破坏面积
                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getMid()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                            break;
                                        case 3:
                                            //严重破坏面积
                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSerious()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                            break;
                                        case 4:
                                            //损坏面积
                                            area = area.add(sfIntensityArea.multiply(buildingVulnerability.getDestroy()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                    }
                                    break;
                                }
                                }
                            }
                        }
                        // //多除以100-----------待修改
                        // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
                        strings[1] = new BigDecimal(strings[1]).add(getStructureLossess2(mapKey, area,
                                buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
                    }
                    map.put(extreme, strings);
                    mapMap.put(key, map);
                }
            }
        }
    }

    private void getYwData2OfPga(Map<String, List<BuildingIndividualEntity>> jggwMap, VillageTownHosPeoEntity villageTownHosPeoEntity
            , BuildingResetUnitPriceEntity buildingPriceEntity, EconomicLosses defaultModel, Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap
            , Map<String, Map<String, String[]>> mapMap, Map<String, Object> param) {
        //key:（Ⅵ，Ⅶ，Ⅷ，Ⅸ，Ⅹ）
        Map<String, String[]> map = null;
        String[] strings = null;
        JSONArray pgaOfYsx = (JSONArray) param.get("pgaOfYsx");
        if (pgaOfYsx == null || pgaOfYsx.size() < 1) {
            return;
        }
        Map<Object, Object> dictItemMap = redisTemplate.opsForHash().entries(FxfzConstants.CACHE_SYS_KEY + "dictItemMap");
        if (dictItemMap == null || dictItemMap.size() < 1) {
            dictItemService.getDictItemMap();
            dictItemMap = redisTemplate.opsForHash().entries(FxfzConstants.CACHE_SYS_KEY + "dictItemMap");
        }
        //建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
        BigDecimal structureDirectLosses = BigDecimal.ZERO;
        //一个obj就是一个网格的一个结构类型的数据
        for (Map.Entry<String, List<BuildingIndividualEntity>> entries1 : jggwMap.entrySet()) {
            String key = entries1.getKey();
            if (mapMap.containsKey(key)) {
                map = mapMap.get(key);
            } else {
                map = new HashMap<>();
            }
            for (BuildingIndividualEntity obj : entries1.getValue()) {
                // if("3d33788670394fdf9120197f048b9854".equals(obj.getExtends1())){
                //     System.out.println();
                // }else {
                //     continue;
                // }
                //如果总面积是0,就不用继续进行了
                // if (obj.getTotalArea() == null || obj.getTotalArea() == 0.0) {
                //     continue;
                // }
                Map<List<String>, List<BigDecimal>> listListMap = null;
                for (String key1 : stringMapMap.keySet()) {
                    //---------待完成；危险性数据和单体数据相关联
                    if (economicLossEDRepository.getSTIntersects(key1, BigDecimal.valueOf(obj.getLongitude()),
                            BigDecimal.valueOf(obj.getLatitude()))) {
                        listListMap = stringMapMap.get(key1);
                        break;
                    }
                }
                //总面积当前坐标总面积
                // BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
                //ysxData的第一个key，结构类型
                String mapKey = dictItemMap.get("100002-" + obj.getStructureType1()) + "";
                if (PlatformObjectUtils.isNotEmpty(obj.getStructureType2())) {
                    switch (obj.getStructureType1()) {
                        case "1":
                            mapKey = mapKey + "-" + dictItemMap.get("100003-" + obj.getStructureType2()) + "";
                            break;
                        case "2":
                            mapKey = mapKey + "-" + dictItemMap.get("100004-" + obj.getStructureType2()) + "";
                            break;
                        case "6":
                            mapKey = mapKey + "-" + dictItemMap.get("100005-" + obj.getStructureType2()) + "";
                            break;
                        default:
                            mapKey = mapKey + "-" + dictItemMap.get(obj.getStructureType2()) + "";
                    }
                }
                //该数据所具备的设防烈度和对应的烈度面积占比结构
                String sfIntensity = dictItemMap.get("100001-" + obj.getDefenceLevel()) + "";//设防烈度
                BigDecimal sfIntensityArea = new BigDecimal(obj.getArea());//设防烈度对应的面积
                //建筑物结构的重置单价
                BigDecimal buildingPrice = BigDecimal.ZERO;
                if (buildingPriceEntity != null) {
                    switch (mapKey) {
                        case "砌体结构-砖混结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
                            break;
                        case "钢筋混凝土结构-剪力墙结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
                            break;
                        case "钢结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
                            break;
                        case "木结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
                            break;
                        case "其他":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
                            break;
                        case "土木结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
                            break;
                        case "钢筋混凝土结构-框架结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
                            break;
                        case "钢筋混凝土结构-框架-剪力墙结构":
                            buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
                                    BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
                            break;
                    }
                }
                //地区室内财产（元/每平米）
                BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
                if ("1".equals(obj.getTownorcontry())) {
                    dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
                } else {
                    dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
                }
                //数据的各个破坏程度的面积
                JSONArray jsonArray = null;
                String[] split = mapKey.split("-");
                if (split.length == 2) {
                    for (int i = 0; i < pgaOfYsx.size(); i++) {
                        JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
                        if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("structureType1").equals(split[1])
                                && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
                            jsonArray = jsonObject.getJSONArray("valueList");
                            break;
                        }
                    }
                } else {
                    for (int i = 0; i < pgaOfYsx.size(); i++) {
                        JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
                        if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
                            jsonArray = jsonObject.getJSONArray("valueList");
                            break;
                        }
                    }
                }
                if (jsonArray == null) {
                    continue;
                }
                //4个破坏程度（轻微，中等，严重，倒塌）
                for (int j = 1; j < 5; j++) {
                    JSONObject jsonObject = null;
                    String extreme = null;
                    String extreme1 = null;
                    switch (j) {
                        case 1:
                            extreme = "pgcd2";
                            extreme1 = "轻微破坏";
                            break;
                        case 2:
                            extreme = "pgcd3";
                            extreme1 = "中等破坏";
                            break;
                        case 3:
                            extreme = "pgcd4";
                            extreme1 = "严重破坏";
                            break;
                        case 4:
                            extreme = "pgcd5";
                            extreme1 = "倒塌";
                    }
                    if (map.containsKey(extreme)) {
                        strings = map.get(extreme);
                    } else {
                        strings = new String[]{obj.getBuildingCode(), BigDecimal.ZERO + ""};
                    }
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        if (jsonObject1.getString("destructiveState").equals(extreme1)) {
                            jsonObject = jsonObject1;
                            break;
                        }
                    }
                    if (jsonObject != null) {
                        if (listListMap != null && listListMap.size() > 0) {
                            BigDecimal area = BigDecimal.ZERO;
                            List<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
                            for (List<String> imList : listListMap.keySet()) {
                                for (int zz=0;zz<imList.size();zz++) {
                                    String im = imList.get(zz);
                                    BigDecimal imValue = values.get(0).get(zz);
                                    BigDecimal funtionValue = publicOperateService.getFuntionValue(jsonObject, im);
                                    area = area.add(sfIntensityArea.multiply(funtionValue).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
                                    //area = imValue.multiply(area);
                                }
                            }
                            // //多除以100-----------待修改
                            // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                            //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
                            strings[1] = new BigDecimal(strings[1]).add(getStructureLossess2(mapKey, area,
                                    buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
                        }
                    }
                    map.put(extreme, strings);
                    mapMap.put(key, map);
                }
            }
        }
    }

    private Map<String, List<BuildingIndividualEntity>> initList1(List<BuildingIndividualEntity> jggwList) {
        Map<String, List<BuildingIndividualEntity>> jggwMap = new HashMap<>();
        List<BuildingIndividualEntity> list = null;
        String key = "";
        for (BuildingIndividualEntity entity : jggwList) {
            key = "Point(" + entity.getLongitude() + " " + entity.getLatitude() + ")";
            if (jggwMap.containsKey(key)) {
                list = jggwMap.get(key);
            } else {
                list = new ArrayList<>();
            }
            list.add(entity);
            jggwMap.put(key, list);
        }
        return jggwMap;
    }

    private BigDecimal getStructureLossess2(String structureType, BigDecimal area, BigDecimal buildingPrice,
                                            EconomicLosses model, BigDecimal indoorPrice, String extreme) {
        //各类损失比
        BigDecimal basic = new BigDecimal(0);
        switch (structureType) {
            case "钢筋混凝土结构-框架-剪力墙结构":
            case "钢筋混凝土结构-剪力墙结构":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight4();
                        break;
                    case "pgcd3":
                        basic = model.getMid4();
                        break;
                    case "pgcd4":
                        basic = model.getSerious4();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy4();
                        break;
                }
                break;
            case "工业厂房-砖混结构厂房":
            case "工业厂房-钢筋混凝土结构厂房":
            case "工业厂房-钢结构厂房":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight8();
                        break;
                    case "pgcd3":
                        basic = model.getMid8();
                        break;
                    case "pgcd4":
                        basic = model.getSerious8();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy8();
                        break;
                }
                break;
            case "砌体结构-砖混结构":
            case "砌体结构-石木结构":
            case "砌体结构-砖木结构":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight5();
                        break;
                    case "pgcd3":
                        basic = model.getMid5();
                        break;
                    case "pgcd4":
                        basic = model.getSerious5();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy5();
                        break;
                }
                break;
            case "钢筋混凝土结构-框架结构":
            case "钢结构":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight3();
                        break;
                    case "pgcd3":
                        basic = model.getMid3();
                        break;
                    case "pgcd4":
                        basic = model.getSerious3();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy3();
                        break;
                }
                break;
            case "土木结构":
            case "木结构":
            case "组合结构":
            case "其他":
                switch (extreme) {
                    case "pgcd2":
                        basic = model.getSlight9();
                        break;
                    case "pgcd3":
                        basic = model.getMid9();
                        break;
                    case "pgcd4":
                        basic = model.getSerious9();
                        break;
                    case "pgcd5":
                        basic = model.getDestroy9();
                        break;
                }
                break;
        }
        //得到建筑物结构经济损失
        BigDecimal structureLossess = model.getStructureLossess();
        BigDecimal lossess = area.multiply(buildingPrice).multiply(basic).multiply(structureLossess).divide(new BigDecimal(1000000), 10, BigDecimal.ROUND_HALF_UP);
        //得到建筑物室内财产经济损失
        BigDecimal indoorLossess = area.multiply(indoorPrice).multiply(basic).multiply(structureLossess).divide(new BigDecimal(1000000), 10, BigDecimal.ROUND_HALF_UP);
        //建筑物直接经济损失
        return lossess.add(indoorLossess);
    }

    private Map<String, Map<String, String[]>> centerEvaluate4(CalculationTasks calculationTasks, EconomicLosses defaultModel
            , Map<String, Object> param, List<VillageTownHosPeoEntity> list1, List<BuildingResetUnitPriceEntity> list2) throws Exception {
        String geom = calculationTasks.getCoordinateRange();
        Map<String, Map<List<String>, List<BigDecimal>>> stringMapMap = null;
        if ("3".equals(calculationTasks.getSeismicInputMode())) {
            //发生概率危险性的数据
            List<PsHazardDataValue> psHazardDataValueList = publicOperateService.getPsHazardDataValueList1(calculationTasks.getLdPga(), geom,calculationTasks);
            if (psHazardDataValueList == null || psHazardDataValueList.size() < 1) {
                return null;
            }
            //转换发生概率危险性的数据的格式
            stringMapMap = publicOperateService.buildPsHazardDataValue(psHazardDataValueList).rowMap();
        } else if ("4".equals(calculationTasks.getSeismicInputMode())) {
            if ("0".equals(calculationTasks.getLdPga())) {
                //烈度
                stringMapMap = publicOperateService.transition1(geom, "", "0").rowMap();
            } else if ("1".equals(calculationTasks.getLdPga())) {
                //pga
                stringMapMap = publicOperateService.transition2(geom, "", "0").rowMap();
            } else {
                throw new RuntimeException("参数2错误，请联系管理员！");
            }
        } else {
            throw new RuntimeException("参数1错误，请联系管理员！");
        }
        /**
         * key: 一个格网
         * value: 一个格网的数据
         * Map<String, String[]>
         *     key: 破坏程度
         *     value: 建筑物直接经济损失
         *
         */
        Map<String, Map<String, String[]>> mapMap = new HashMap<>();
        String province = null, city = null, county = null;
        //烈度
        Map<String, Map<String, Map<String, BuildingVulnerability>>> ldOfYsx = null;
        //pga
        JSONArray pgaOfYsx = null;
        //人口与建筑物数据
        VillageTownHosPeoEntity villageTownHosPeoEntity = null;
        //建筑物结构重置单价
        BuildingResetUnitPriceEntity buildingPriceEntity = null;
//         //数据视图条件
//         QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
//         //写入条件版本号
//         queryByVersionParam.setVersionCode(calculationTasks.getHouseData());
// //                        //获取区县code
// //                         //0为省市区县1为地图圈选
//         queryByVersionParam.setGeomType(1);
//         queryByVersionParam.setGeom(calculationTasks.getCoordinateRange());
        //房屋单体数据
        List<BuildingIndividualEntity> jggwList = calculationTasksRepository.getMonomerDate(calculationTasks.getId());
        Map<String, List<BuildingIndividualEntity>> jggwMap = initList2(jggwList);
        //根据字典值获取不同结构类型的具体数据并计算
        if (PlatformObjectUtils.isNotEmpty(jggwList) && jggwList.size() > 0) {
            //key:（Ⅵ，Ⅶ，Ⅷ，Ⅸ，Ⅹ）
            Map<String, String[]> map = null;
            String[] strings = null;
            //易损性数据
            Map<Object, Object> dictItemMap = redisTemplate.opsForHash().entries(FxfzConstants.CACHE_SYS_KEY + "dictItemMap");
            if (dictItemMap.size() < 1) {
                dictItemService.getDictItemMap();
                dictItemMap = redisTemplate.opsForHash().entries(FxfzConstants.CACHE_SYS_KEY + "dictItemMap");
            }
            //建筑物直接经济损失由建筑物结构经济损失和建筑物室内财产经济损失组成
            BigDecimal structureDirectLosses = BigDecimal.ZERO;
            if ("0".equals(calculationTasks.getLdPga())) {
                //烈度
                //一个obj就是一个网格的一个结构类型的数据
                for (Map.Entry<String, List<BuildingIndividualEntity>> entries1 : jggwMap.entrySet()) {
                    String key = entries1.getKey();
                    String[] split = key.split("-");
                    if (PlatformObjectUtils.isEmpty(split[0]) || PlatformObjectUtils.isEmpty(split[1]) || PlatformObjectUtils.isEmpty(split[2])) {
                        continue;
                    }
                    if (!split[0].equals(province) || !split[1].equals(city) || !split[2].equals(county)) {
                        //人口与建筑物数据
                        villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCityForName(split[0], split[1], split[2], "");
                        if(villageTownHosPeoEntity == null){
                            throw new Exception("该区域内"+split[0]+split[1]+split[2]+"的人口与建筑物数据未设置");
                        }
                        //建筑物结构重置单价
                        buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvinceName(split[0], split[1], split[2]);
                        if(buildingPriceEntity == null){
                            throw new Exception("该区域内"+split[0]+split[1]+split[2]+"的建筑物结构重置单价未设置");
                        }
                        list1.add(villageTownHosPeoEntity);
                        list2.add(buildingPriceEntity);
                        if ("1".equals(calculationTasks.getLdPga())) {
                            //烈度
                            ldOfYsx = ysxUtil.getYSX(calculationTasks.getId(), split[0], split[1], split[2]);
                        } else {
                            //pga
                            pgaOfYsx = jcsjRestManager.getPgaOfYsx(split[0], split[1], split[2]);
                        }
                    }
                    if (mapMap.containsKey(key)) {
                        map = mapMap.get(key);
                    } else {
                        map = new HashMap<>();
                    }
                    for (BuildingIndividualEntity obj : entries1.getValue()) {
                        // if("3d33788670394fdf9120197f048b9854".equals(obj.getExtends1())){
                        //     System.out.println();
                        // }else {
                        //     continue;
                        // }
                        //如果总面积是0,就不用继续进行了
                        // if (obj.getTotalArea() == null || obj.getTotalArea() == 0.0) {
                        //     continue;
                        // }
                        if (PlatformObjectUtils.isEmpty(obj.getProvince()) || PlatformObjectUtils.isEmpty(obj.getCity()) || PlatformObjectUtils.isEmpty(obj.getCounty())) {
                            continue;
                        }
                        //一个公里网格下的危险性数据，年平均发生概率，key为X轴(im)，value为Y轴(年平均发生概率)
                        Map<List<String>, List<BigDecimal>> listListMap = null;
                        for (String key1 : stringMapMap.keySet()) {
                            //---------待完成；危险性数据和单体数据相关联
                            if (economicLossEDRepository.getSTIntersects(key1, BigDecimal.valueOf(obj.getLongitude()),
                                    BigDecimal.valueOf(obj.getLatitude()))) {
                                listListMap = stringMapMap.get(key1);
                                break;
                            }
                        }
                        //总面积当前坐标总面积
                        // BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
                        //ysxData的第一个key，结构类型
                        String mapKey = dictItemMap.get("100002-" + obj.getStructureType1()) + "";
                        if (PlatformObjectUtils.isNotEmpty(obj.getStructureType2())) {
                            switch (obj.getStructureType1()) {
                                case "1":
                                    mapKey = mapKey + "-" + dictItemMap.get("100003-" + obj.getStructureType2()) + "";
                                    break;
                                case "2":
                                    mapKey = mapKey + "-" + dictItemMap.get("100004-" + obj.getStructureType2()) + "";
                                    break;
                                case "6":
                                    mapKey = mapKey + "-" + dictItemMap.get("100005-" + obj.getStructureType2()) + "";
                                    break;
                                default:
                                    mapKey = mapKey + "-" + dictItemMap.get(obj.getStructureType2()) + "";
                            }
                        }
                        //当前结构的易损性数据
                        Map<String, Map<String, BuildingVulnerability>> sfIntensityMap = ldOfYsx.get(mapKey);
                        if (sfIntensityMap == null || sfIntensityMap.size() < 1) {
                            continue;
                        }
                        //该数据所具备的设防烈度和对应的烈度面积占比结构
                        String sfIntensity = dictItemMap.get("100001-" + obj.getDefenceLevel()) + "";//设防烈度
                        BigDecimal sfIntensityArea = new BigDecimal(obj.getArea());//设防烈度对应的面积
                        //建筑物结构的重置单价
                        BigDecimal buildingPrice = BigDecimal.ZERO;
                        if (buildingPriceEntity != null) {
                            switch (mapKey) {
                                case "砌体结构-砖混结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
                                    break;
                                case "钢筋混凝土结构-剪力墙结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
                                    break;
                                case "钢结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
                                    break;
                                case "木结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
                                    break;
                                case "其他":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
                                    break;
                                case "土木结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
                                    break;
                                case "钢筋混凝土结构-框架结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
                                    break;
                                case "钢筋混凝土结构-框架-剪力墙结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
                                    break;
                            }
                        }
                        //地区室内财产（元/每平米）
                        BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
                        if ("1".equals(obj.getTownorcontry())) {
                            dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
                        } else {
                            dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
                        }
                        //易损性数据下设防烈度对应的数据
                        Map<String, BuildingVulnerability> vulnerabilityList = null;
                        try {
                            vulnerabilityList = sfIntensityMap.get(sfIntensity);
                        } catch (NullPointerException e) {
                            e.printStackTrace();
                        }
                        //4个破坏程度（轻微，中等，严重，倒塌）
                        for (int j = 1; j < 5; j++) {
                            String extreme = null;
                            switch (j) {
                                case 1:
                                    extreme = "pgcd2";
                                    break;
                                case 2:
                                    extreme = "pgcd3";
                                    break;
                                case 3:
                                    extreme = "pgcd4";
                                    break;
                                case 4:
                                    extreme = "pgcd5";
                            }
                            if (map.containsKey(extreme)) {
                                strings = map.get(extreme);
                            } else {
                                strings = new String[]{obj.getBuildingCode(), BigDecimal.ZERO + ""};
                            }
                            if (listListMap != null && listListMap.size() > 0) {
                                BigDecimal area = BigDecimal.ZERO;
                                ArrayList<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
                                for (List<String> imList : listListMap.keySet()) {
                                    //遍历烈度
                                    for (int zz=0;zz<imList.size();zz++) {
                                        String im = imList.get(zz);
                                        BigDecimal imValue = values.get(0).get(zz);
                                        String realIntensity = getRealIntensity(im);
                                        if (vulnerabilityList != null && vulnerabilityList.size() >0) {
                                        BuildingVulnerability buildingVulnerability = vulnerabilityList.get(realIntensity);
                                        if (buildingVulnerability != null) {
                                            switch (j) {
                                                case 1:
                                                    //轻微破坏面积
                                                    area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSlight()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                    break;
                                                case 2:
                                                    //中等破坏面积
                                                    area = area.add(sfIntensityArea.multiply(buildingVulnerability.getMid()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                    break;
                                                case 3:
                                                    //严重破坏面积
                                                    area = area.add(sfIntensityArea.multiply(buildingVulnerability.getSerious()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                                    break;
                                                case 4:
                                                    //损坏面积
                                                    area = area.add(sfIntensityArea.multiply(buildingVulnerability.getDestroy()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP).multiply(imValue));
                                            }
                                            break;
                                        }
                                        }
                                    }
                                }
                                // //多除以100-----------待修改
                                // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                                //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
                                strings[1] = new BigDecimal(strings[1]).add(getStructureLossess2(mapKey, area,
                                        buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
                            }
                            map.put(extreme, strings);
                        }
                    }
                    mapMap.put(key, map);

                    province = split[0];
                    city = split[1];
                    county = split[2];
                }
            } else {
                //pga
                //一个obj就是一个网格的一个结构类型的数据
                for (Map.Entry<String, List<BuildingIndividualEntity>> entries1 : jggwMap.entrySet()) {
                    String key = entries1.getKey();
                    String[] split = key.split("-");
                    if (PlatformObjectUtils.isEmpty(split[0]) || PlatformObjectUtils.isEmpty(split[1]) || PlatformObjectUtils.isEmpty(split[2])) {
                        continue;
                    }
                    if (!split[0].equals(province) || !split[1].equals(city) || !split[2].equals(county)) {
                        //人口与建筑物数据
                        villageTownHosPeoEntity = villageTownHostPeoService.findByProvinceAndCityForName(split[0], split[1], split[2], "");
                        if(villageTownHosPeoEntity == null){
                            throw new Exception("该区域内"+split[0]+split[1]+split[2]+"的人口与建筑物数据未设置");
                        }
                        //建筑物结构重置单价
                        buildingPriceEntity = buildingResetUnitPriceRepository.findByPronvinceName(split[0], split[1], split[2]);
                        if(buildingPriceEntity == null){
                            throw new Exception("该区域内"+split[0]+split[1]+split[2]+"的建筑物结构重置单价未设置");
                        }
                        list1.add(villageTownHosPeoEntity);
                        list2.add(buildingPriceEntity);
                        if ("1".equals(calculationTasks.getLdPga())) {
                            //烈度
                            ldOfYsx = ysxUtil.getYSX(calculationTasks.getId(), split[0], split[1], split[2]);
                        } else {
                            //pga
                            pgaOfYsx = jcsjRestManager.getPgaOfYsx(split[0], split[1], split[2]);
                        }
                    }
                    if (mapMap.containsKey(key)) {
                        map = mapMap.get(key);
                    } else {
                        map = new HashMap<>();
                    }
                    for (BuildingIndividualEntity obj : entries1.getValue()) {
                        // if("3d33788670394fdf9120197f048b9854".equals(obj.getExtends1())){
                        //     System.out.println();
                        // }else {
                        //     continue;
                        // }
                        //如果总面积是0,就不用继续进行了
                        // if (obj.getTotalArea() == null || obj.getTotalArea() == 0.0) {
                        //     continue;
                        // }
                        Map<List<String>, List<BigDecimal>> listListMap = null;
                        for (String key1 : stringMapMap.keySet()) {
                            //---------待完成；危险性数据和单体数据相关联
                            if (economicLossEDRepository.getSTIntersects(key1, BigDecimal.valueOf(obj.getLongitude()),
                                    BigDecimal.valueOf(obj.getLatitude()))) {
                                listListMap = stringMapMap.get(key1);
                                break;
                            }
                        }
                        //总面积当前坐标总面积
                        // BigDecimal totalArea = obj.getTotalArea() == null ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea());
                        //ysxData的第一个key，结构类型
                        String mapKey = dictItemMap.get("100002-" + obj.getStructureType1()) + "";
                        if (PlatformObjectUtils.isNotEmpty(obj.getStructureType2())) {
                            switch (obj.getStructureType1()) {
                                case "1":
                                    mapKey = mapKey + "-" + dictItemMap.get("100003-" + obj.getStructureType2()) + "";
                                    break;
                                case "2":
                                    mapKey = mapKey + "-" + dictItemMap.get("100004-" + obj.getStructureType2()) + "";
                                    break;
                                case "6":
                                    mapKey = mapKey + "-" + dictItemMap.get("100005-" + obj.getStructureType2()) + "";
                                    break;
                                default:
                                    mapKey = mapKey + "-" + dictItemMap.get(obj.getStructureType2()) + "";
                            }
                        }
                        //该数据所具备的设防烈度和对应的烈度面积占比结构
                        String sfIntensity = dictItemMap.get("100001-" + obj.getDefenceLevel()) + "";//设防烈度
                        BigDecimal sfIntensityArea = new BigDecimal(obj.getArea());//设防烈度对应的面积
                        //建筑物结构的重置单价
                        BigDecimal buildingPrice = BigDecimal.ZERO;
                        if (buildingPriceEntity != null) {
                            switch (mapKey) {
                                case "砌体结构-砖混结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getBrickConcrete()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getBrickConcrete());
                                    break;
                                case "钢筋混凝土结构-剪力墙结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteShearWall()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteShearWall());
                                    break;
                                case "钢结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSteel()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSteel());
                                    break;
                                case "木结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getWood()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getWood());
                                    break;
                                case "其他":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getOther()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getOther());
                                    break;
                                case "土木结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getSoilWood()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getSoilWood());
                                    break;
                                case "钢筋混凝土结构-框架结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrame()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrame());
                                    break;
                                case "钢筋混凝土结构-框架-剪力墙结构":
                                    buildingPrice = PlatformObjectUtils.isEmpty(buildingPriceEntity.getReinforcedConcreteFrameShearWall()) ?
                                            BigDecimal.ZERO : new BigDecimal(buildingPriceEntity.getReinforcedConcreteFrameShearWall());
                                    break;
                            }
                        }
                        //地区室内财产（元/每平米）
                        BigDecimal dhpIndoorProperty = BigDecimal.ZERO;
                        if ("1".equals(obj.getTownorcontry())) {
                            dhpIndoorProperty = villageTownHosPeoEntity.getDhpTownIndoorProperty();
                        } else {
                            dhpIndoorProperty = villageTownHosPeoEntity.getDhpVillageIndoorProperty();
                        }
                        //数据的各个破坏程度的面积
                        JSONArray jsonArray = null;
                        String[] split1 = mapKey.split("-");
                        if (split1.length == 2) {
                            for (int i = 0; i < pgaOfYsx.size(); i++) {
                                JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
                                if (jsonObject.getString("structureType").equals(split1[0]) && jsonObject.getString("structureType1").equals(split1[1])
                                        && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
                                    jsonArray = jsonObject.getJSONArray("valueList");
                                    break;
                                }
                            }
                        } else {
                            for (int i = 0; i < pgaOfYsx.size(); i++) {
                                JSONObject jsonObject = pgaOfYsx.getJSONObject(i);
                                if (jsonObject.getString("structureType").equals(split[0]) && jsonObject.getString("defenseSituation").equals(sfIntensity)) {
                                    jsonArray = jsonObject.getJSONArray("valueList");
                                    break;
                                }
                            }
                        }
                        if (jsonArray == null) {
                            continue;
                        }
                        //4个破坏程度（轻微，中等，严重，倒塌）
                        for (int j = 1; j < 5; j++) {
                            JSONObject jsonObject = null;
                            String extreme = null;
                            String extreme1 = null;
                            switch (j) {
                                case 1:
                                    extreme = "pgcd2";
                                    extreme1 = "轻微破坏";
                                    break;
                                case 2:
                                    extreme = "pgcd3";
                                    extreme1 = "中等破坏";
                                    break;
                                case 3:
                                    extreme = "pgcd4";
                                    extreme1 = "严重破坏";
                                    break;
                                case 4:
                                    extreme = "pgcd5";
                                    extreme1 = "倒塌";
                            }
                            if (map.containsKey(extreme)) {
                                strings = map.get(extreme);
                            } else {
                                strings = new String[]{obj.getBuildingCode(), BigDecimal.ZERO + ""};
                            }
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                                if (jsonObject1.getString("destructiveState").equals(extreme1)) {
                                    jsonObject = jsonObject1;
                                    break;
                                }
                            }
                            if (jsonObject != null) {
                                if (listListMap != null && listListMap.size() > 0) {
                                    BigDecimal area = BigDecimal.ZERO;
                                    ArrayList<List<BigDecimal>> values = new ArrayList<>(listListMap.values());
                                    for (List<String> imList : listListMap.keySet()) {
                                        for (int zz=0;zz<imList.size();zz++) {
                                            String im = imList.get(zz);
                                            BigDecimal imValue = values.get(0).get(zz);
                                            BigDecimal funtionValue = publicOperateService.getFuntionValue(jsonObject, im);
                                            area = area.add(sfIntensityArea.multiply(funtionValue).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
                                            //area = area.multiply(imValue);
                                        }
                                    }
                                    // //多除以100-----------待修改
                                    // area = area.divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                                    //获取每类建筑结构在每个地震烈度下的建筑物直接经济损失
                                    strings[1] = new BigDecimal(strings[1]).add(getStructureLossess2(mapKey, area,
                                            buildingPrice, defaultModel, dhpIndoorProperty, extreme)) + "";
                                }
                            }
                            map.put(extreme, strings);
                        }
                    }
                    mapMap.put(key, map);

                    province = split[0];
                    city = split[1];
                    county = split[2];
                }
            }
        }
        return mapMap;
    }

    private Map<String, List<BuildingIndividualEntity>> initList2(List<BuildingIndividualEntity> jggwList) {
        Map<String, List<BuildingIndividualEntity>> jggwMap = new HashMap<>();
        List<BuildingIndividualEntity> list = null;
        String key = "";
        for (BuildingIndividualEntity entity : jggwList) {
            key = entity.getProvince() + "-" + entity.getCity() + "-" + entity.getCounty() + "-Point(" + entity.getLongitude() + " " + entity.getLatitude() + ")";
            if (jggwMap.containsKey(key)) {
                list = jggwMap.get(key);
            } else {
                list = new ArrayList<>();
            }
            list.add(entity);
            jggwMap.put(key, list);
        }
        return jggwMap;
    }

    //导入
    @Override
    public String reportImport(InputStream inputStream, String type, String id, String years, String code) {
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(inputStream);

            Map<String, Object> map = getList(workbook, type, id, years, code);
            Object o = map.get("message");
            if (o != null) {
                return String.valueOf(o);
            } else {
                List<EconomicLossPDCalculation> list = (List<EconomicLossPDCalculation>) map.get("list");
                economicLossPDRepository.batchCalculation(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "成功";
    }

    public static int USE_SXSSF_LIMIT = 100000;

    //导出
    @Override
    public void exportData(HttpServletResponse response, EconomicLossPECalculationParam param) {
        try {
            //查询省市县
            List<EconomicLossPCCPEVO> list = economicLossPDRepository.getListPCC(param);
            Workbook workbook = (Workbook) (list.size() < USE_SXSSF_LIMIT ? new XSSFWorkbook() : new SXSSFWorkbook());
            // 全局样式设置
            CellStyle allStyle = workbook.createCellStyle();
            allStyle.setFillPattern(FillPatternType.NO_FILL); // 背景
            allStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());// 填充白色
            allStyle.setBorderBottom(BorderStyle.THIN); // 下边框
            allStyle.setBorderLeft(BorderStyle.THIN);// 左边框
            allStyle.setBorderTop(BorderStyle.THIN);// 上边框
            allStyle.setBorderRight(BorderStyle.THIN);// 右边框
            allStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
            allStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            allStyle.setWrapText(true);//自动换行

            String[] sheetHeadTitle = new String[]{"省", "市", "区(县)", "地理id(虚拟ID)", "破坏程度", "计算值(万元)", "修改值(万元)"
                    ,  "期望值（万元）"};
            Sheet sheet = workbook.createSheet("经济损失");
            // 设置自动列宽
            for (int i = 0; i < sheetHeadTitle.length; i++) {
                sheet.autoSizeColumn(i);
                sheet.setColumnWidth(i, 20*256);
            }
            String[] values = null;
            BigDecimal expectValue = BigDecimal.ZERO;
            for (int i = 0; i < list.size() + 2; i++) {
                if (i > 1) {
                    values = CheckObjFields.objectChangeArray(list.get(i - 2));
                }
                Row row_i = sheet.createRow(i);
                for (int j = 0; j < sheetHeadTitle.length; j++) {
                    Cell celli_j = row_i.createCell(j, CellType.STRING);
                    if (i == 0) {
                        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, sheetHeadTitle.length - 1));
                        celli_j.setCellValue("经济损失");
                        celli_j.setCellStyle(allStyle);
                        break;
                    } else if (i == 1) {
                        celli_j.setCellValue(sheetHeadTitle[j]);
                    } else {
                        if (j == sheetHeadTitle.length - 1) {
                            if ((i - 1) % 4 == 0) {
                                sheet.addMergedRegion(new CellRangeAddress(i - 3, i, j, j));
                                Row row = sheet.getRow(i - 3);
                                Cell cell = row.getCell(j);
                                expectValue = expectValue.add(new BigDecimal(values[j-1]));
                                cell.setCellValue(expectValue + "");
                                cell.setCellStyle(allStyle);
                                expectValue = BigDecimal.ZERO;
                            } else {
                                expectValue = expectValue.add(new BigDecimal(values[j-1]));
                            }
                        } else {
                            if (values[j] == null) {
                                continue;
                            }
                            celli_j.setCellValue(values[j]);
                        }
                    }
                    celli_j.setCellStyle(allStyle);
                }
                sheet.autoSizeColumn((short) i);
            }
            // 07版本
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("经济损失概率评估计算.xlsx", "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

    //查询计算值
    @Override
    public Map<String, Object> queryCalculation(int curPage, int pageSize, String id, String years) {
        return economicLossPDRepository.queryCalculation(curPage, pageSize, id, years);
    }

    //修改概率P(t)修正值
    @Override
    public void updateCorrectionValue(EconomicLossPDCalculation param) {
//        //BigDecimal chancePt = new BigDecimal(param.getChancePt());
//        BigDecimal correctionValue = new BigDecimal(param.getCorrectionValue());
//        //期望值（万元）
//        param.setExpectValue(chancePt.multiply(correctionValue));
        economicLossPDRepository.updateCorrectionValue(param);
    }

    @Override
    public List<FxqhAssessPdQhResult> doZoning(CalculationTasks task) throws Exception {
        List<FxqhAssessPdQhResult> resultList = new ArrayList<>();
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        List<PCC> pccList = null;
//        if (task.getRadio2().equals("0")) {
        pccList = task.getList();
//        } else {
//            pccList = pccRepository.queryToponym(task.getId());
//        }
        String seiMode = null;
        if (task.getSeismicInputMode().contains("3")) {
            //发生概率
            seiMode = "0";
        } else if (task.getSeismicInputMode().contains("4")) {
            //超越概率
            seiMode = "1";
        } else {
            throw new RuntimeException("没有概率评估，不能进行概率评估风险区划！");
        }
        Map<String, Map<String, List<Map<String, Object>>>> listMapMap = new HashMap<>();
        Map<String, List<Map<String, Object>>> listMap = null;
        List<Map<String, Object>> mapList = null;
        List<Map<String, Object>> list = economicLossPDRepository.getSumByTaskId(task.getId());
        if(PlatformObjectUtils.isNotEmpty(list) && list.size()>0){
            for (Map<String, Object> map : list) {
                String key1 = map.get("provinceName") + "-" + map.get("cityName") + "-" + map.get("countyName");
                if (listMapMap.containsKey(key1)) {
                    listMap = listMapMap.get(key1);
                } else {
                    listMap = new HashMap<>();
                }
                if (listMap.containsKey(map.get("years") + "")) {
                    mapList = listMap.get(map.get("years") + "");
                } else {
                    mapList = new ArrayList<>();
                }
                mapList.add(map);
                listMap.put(map.get("years") + "", mapList);
                listMapMap.put(key1, listMap);
            }
        }

        // for (String seiMode : task.getSeismicInputMode().split(",")) {
        // if (!seiMode.equals("3")) {
        //     continue;
        // }
        Map<String, List<Map<String, Object>>> listMap1 = null;
        List<Map<String, Object>> mapList1 = null;
        if(listMapMap.values().size()>0){
            for (PCC pcc : pccList) {
                //获取区县上一年的GDP
                GdpVO gdp = enterAssessQhRepository.getGdpByTaskIdAndDistrict(task.getId(),pcc.getPpName(),pcc.getCityName(),pcc.getName());
                if(gdp == null){
                    throw new RuntimeException("计算未完成，没有获取到"+pcc.getPpName()+pcc.getCityName()+pcc.getName()+"上年度 GDP！");
                }
                listMap1 = listMapMap.get(pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName());
                String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(pcc.getPpName(), "UTF-8"),
                        URLEncoder.encode(pcc.getCityName(), "UTF-8"), URLEncoder.encode(pcc.getName(), "UTF-8"));
                String code = null;
                if (areaIdCodeMap == null || areaIdCodeMap.size() < 1) {
                    code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
                } else {
                    code = areaIdCodeMap.get(divisionIds.split("_")[2]);
                }
                String geom = jcsjRestManager.getGeomByCode(code, "3");
                if (geom == null) {
                    continue;
                    // throw new RuntimeException("未获取到" + pcc.getPpName() + pcc.getCityName() + pcc.getName() + "的空间数据！");
                }
                for (String years : task.getYear().split(",")) {
                    mapList1 = listMap1.get(years);
                    // List<Map<String, Object>> list = economicLossPDRepository.getSumByDivisionAndAssessCodes(pcc.getPpName(), pcc.getCityName(), pcc.getName(),
                    //         task.getId(), years, seiMode);g
                    BigDecimal calculatedValue = BigDecimal.ZERO;
                    for (int i = 0; i < mapList1.size(); i++) {
                        Map<String, Object> map = mapList1.get(i);
                        // if (i == 0 && ((Long) map.get("count")) > 1) {
                        //     throw new RuntimeException("所选评估记录中有重复区县，请重新选择！");
                        // }
                        calculatedValue = calculatedValue.add(BigDecimal.valueOf((Double) map.get("sum")));
                    }
                    //根据确定评估-经济损失中的计算值，取四类破坏状态（轻微、中等、严重、毁坏）下的经济损失值之和/区域内上年度 GDP。
                    calculatedValue = calculatedValue.divide(gdp.getPreviousGdp(),6, RoundingMode.HALF_DOWN);
                    FxqhAssessPdQhResult result = new FxqhAssessPdQhResult();
                    result.setProvince(pcc.getPpName());
                    result.setCity(pcc.getCityName());
                    result.setCounty(pcc.getName());
                    if ("新疆维吾尔自治区".equals(pcc.getPpName()) || "青海省".equals(pcc.getPpName()) || "西藏自治区".equals(pcc.getPpName())) {
                        result.setBorderlandFlag("1");
                    } else {
                        result.setBorderlandFlag("0");
                    }
                    if (mapList1.size() > 0) {
                        result.setCalculatedValue(calculatedValue);
                    } else {
                        result.setCalculatedValue(BigDecimal.ZERO);
                    }
                    result.setId(UUIDGenerator.getUUID());
                    result.setTaskId(task.getId());
                    result.setEstimateObj("2");
                    result.setHouseDataFlag(task.getHouseDataFlag());
                    result.setCondition(years);
                    result.setSeismicInputMode(seiMode);
                    result.setGeom(geom);
                    resultList.add(result);
                }
            }
        }
        // }
        return resultList;
    }

    //获取list
    private Map<String, Object> getList(Workbook workbook, String type, String id, String years, String code) throws UnsupportedEncodingException {
        String userID = PlatformSessionContext.getUserID();
        Map<String, Object> map = new HashMap<>();
        List<EconomicLossPDCalculation> list = new ArrayList<>();
        Boolean mark = true;
//        if (type.equals("2")) {
//            mark = false;
//        }
        if (workbook != null) {
            //循环除了第一行的所有行
            /** 得到第一个sheet */
            Sheet sheet = workbook.getSheetAt(0);
            /** 得到Excel的行数 */
            int totalRows = sheet.getPhysicalNumberOfRows();
            HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
            /** 循环Excel的行 从第4行开始*/
            for (int r = 2; r < totalRows; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                EconomicLossPDCalculation obj = new EconomicLossPDCalculation();
                if (mark) {
                    //按照省市县输入时校验
                    Map<String, Object> check = check(row, type);
                    //如果没有message
                    if (check.get("message") == null) {
                        //省
                        obj.setProvinceName(hSSFDataFormatter.formatCellValue(row.getCell(0)));
                        //市
                        obj.setCityName(hSSFDataFormatter.formatCellValue(row.getCell(1)));
                        //县
                        obj.setCountyName(hSSFDataFormatter.formatCellValue(row.getCell(2)));
                        //建筑物公里网格ID（建筑物单体ID）
                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(3)));
                        //破坏程度(轻微,中等,严重,倒塌)
                        String extreme = hSSFDataFormatter.formatCellValue(row.getCell(4));
                        if("轻微破坏".equals(extreme)){
                            extreme = "pgcd2";
                        }else if("中等破坏".equals(extreme)){
                            extreme = "pgcd3";
                        }else if("严重破坏".equals(extreme)){
                            extreme = "pgcd4";
                        }else if("倒塌".equals(extreme)){
                            extreme = "pgcd5";
                        }
                        obj.setExtreme(extreme);
                        //计算着(万元)
                        obj.setCalculatedValue(hSSFDataFormatter.formatCellValue(row.getCell(5)));
                        //修改值(万元)
                        obj.setCorrectionValue(hSSFDataFormatter.formatCellValue(row.getCell(6)));
                       /* //概率P(t)计算值
                        obj.setCalculatedValueP1(hSSFDataFormatter.formatCellValue(row.getCell(7)));
                        //概率P(t)修正值
                        obj.setCorrectionValueP1(hSSFDataFormatter.formatCellValue(row.getCell(8)));
                        //概率值p(T)(用【概率P(1)修正值】进行计算
                        obj.setChancePt(hSSFDataFormatter.formatCellValue(row.getCell(9)));*/
//                        //期望值（万元）
//                        obj.setExpectValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(10))));
                    } else {
                        return check;
                    }
                } else {
                    //按照坐标范围输入时校验
                    Map<String, Object> check = check2(row, type);
                    //如果没有message
                    if (check.get("message") == null) {
                        //经纬度坐标范围
                        obj.setCoordinateRange(hSSFDataFormatter.formatCellValue(row.getCell(0)));
                        //建筑物公里网格ID（建筑物单体ID）
                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(1)));
                        //破坏程度(轻微,中等,严重,倒塌)
                        obj.setExtreme(hSSFDataFormatter.formatCellValue(row.getCell(2)));
                        //计算着(万元)
                        obj.setCalculatedValue(hSSFDataFormatter.formatCellValue(row.getCell(3)));
                        //修改值(万元)
                        obj.setCorrectionValue(hSSFDataFormatter.formatCellValue(row.getCell(4)));
                   /*     //概率P(t)计算值
                        obj.setCalculatedValueP1(hSSFDataFormatter.formatCellValue(row.getCell(5)));
                        //概率P(t)修正值
                        obj.setCorrectionValueP1(hSSFDataFormatter.formatCellValue(row.getCell(6)));
                        //概率值p(T)(用【概率P(1)修正值】进行计算
                        obj.setChancePt(hSSFDataFormatter.formatCellValue(row.getCell(7)));*/
                        //期望值（万元）
                        obj.setExpectValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(8))));
                    } else {
                        return check;
                    }
                }
                //评估记录id
                obj.setAssessId(id);
                obj.setAssessCode(code);
                //主键id
                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //创建人
                obj.setCreateUser(userID);
                //创建时间
                obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                //T年
                obj.setYears(years);
                obj.setDelFlag("0");
                list.add(obj);
            }
        }
        map.put("list", list);
        return map;
    }

    //数据校验省市县
    private Map<String, Object> check(Row row, String type) throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<>();
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(0)))) {
            map.put("message", "省不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(1)))) {
            map.put("message", "市不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
            map.put("message", "县不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(3)))) {
            map.put("message", "建筑物公里网格ID（建筑物单体ID）不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
            map.put("message", "破坏程度不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(5)))) {
            map.put("message", "计算值（万元）不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(6)))) {
            map.put("message", "修正值（万元）不能为空");
        }
//        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(7)))) {
//            map.put("message", "概率P（1）计算值不能为空");
//        }
//        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(8)))) {
//            map.put("message", "概率P（1）修正值不能为空");
//        }
//        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(9)))) {
//            map.put("message", "概率值p(T)(用【概率P(1)修正值】进行计算）不能为空");
//        }
//        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(10)))) {
//            map.put("message", "期望值（万元)不能为空");
//        }
        String province = hSSFDataFormatter.formatCellValue(row.getCell(0));
        String city = hSSFDataFormatter.formatCellValue(row.getCell(1));
        String county = hSSFDataFormatter.formatCellValue(row.getCell(2));
        // 根据省市县名称获得省市县id _ 分割
        String divisionIds = sysAreaService.getIdByCondition(
                URLEncoder.encode(province, "UTF-8"),
                URLEncoder.encode(city, "UTF-8"),
                URLEncoder.encode(county, "UTF-8"));
        if (divisionIds == null) {
            map.put("message", "省市县错误" + province + "_" + city + "_" + county);
        }
        String[] s = divisionIds.split("_");
        if (s.length != 3) {
            map.put("message", "省市县错误" + province + "_" + city + "_" + county);
        }
        return map;
    }

    //范围校验
    private Map<String, Object> check2(Row row, String type) throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<>();
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(0)))) {
            map.put("message", "坐标范围不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(1)))) {
            map.put("message", "建筑物公里网格ID（建筑物单体ID）不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
            map.put("message", "破坏程度不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(3)))) {
            map.put("message", "计算值（万元）不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
            map.put("message", "修正值（万元）不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(5)))) {
            map.put("message", "概率P（1）计算值不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(6)))) {
            map.put("message", "概率P（1）修正值不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(7)))) {
            map.put("message", "概率值p(T)(用【概率P(1)修正值】进行计算）不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(8)))) {
            map.put("message", "期望值（万元)不能为空");
        }
        return map;
    }

//    @Override
//    public List<Statistics> statistics(String taskId) {
//        List<EconomicLossPDCalculation> list = economicLossPDRepository.getByTaskId(taskId);
//        //获取评估任务关联的省市区县
//        List<PCC> pccs = pccRepository.queryToponym(taskId);
//        if(PlatformObjectUtils.isEmpty(pccs) || pccs.size() == 0){
//            throw new RuntimeException("任务没有关联任何评估区域");
//        }
//        List<String> provinceList = pccs.stream().map(PCC::getPpName).distinct().collect(Collectors.toList());
//        List<Statistics> resultList = new ArrayList<>();
//        for (String province : provinceList) {
//            List<EconomicLossPDCalculation> pList = list.stream().filter(economicLossPDCalculation -> province.equals(economicLossPDCalculation.getProvinceName())).collect(Collectors.toList());
//            Map<String, List<EconomicLossPDCalculation>> collectMap = pList.stream().collect(Collectors.groupingBy(EconomicLossPDCalculation::getExtreme));
//            List<String> cityList = pccs.stream().filter(pcc->province.equals(pcc.getPpName())).map(PCC::getCityName).distinct().collect(Collectors.toList());
//            for (String extreme : extremeList()) {
//                List<EconomicLossPDCalculation> casualtiesPECalculations = collectMap.get(extreme);
//                BigDecimal proTotal = casualtiesPECalculations.stream()
//                        .map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())) // 提取每个RiskAnalysisDeductDetail的Score字段
//                        .reduce(BigDecimal.ZERO, BigDecimal::add);
//                Statistics proStatistics = buildEntityData(province,proTotal,extreme);
//                List<Statistics> cityChildren = new ArrayList<>();
//                for (String city : cityList) {
//                    List<String> countyList = pccs.stream().filter(pcc->city.equals(pcc.getCityName())).map(PCC::getName).distinct().collect(Collectors.toList());
//                    BigDecimal cityTotal = casualtiesPECalculations.stream().filter(casualtiesPECalculation -> {
//                        return city.equals(casualtiesPECalculation.getCityName());
//                    }).map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())).
//                            reduce(BigDecimal.ZERO, BigDecimal::add);
//                    Statistics cityStatistics = buildEntityData(city,cityTotal,extreme);
//                    List<Statistics> countyChildren = new ArrayList<>();
//                    for (String county : countyList) {
//                        BigDecimal countyTotal = casualtiesPECalculations.stream().filter(casualtiesPECalculation -> {
//                            return county.equals(casualtiesPECalculation.getCountyName());
//                        }).map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        Statistics countyStatistics = buildEntityData(county,countyTotal,extreme);
//                        countyChildren.add(countyStatistics);
//                    }
//                    cityStatistics.setChildren(countyChildren);
//                    cityChildren.add(cityStatistics);
//                }
//                proStatistics.setChildren(cityChildren);
//                resultList.add(proStatistics);
//            }
//        }
//        return resultList;
//    }
    @Override
    public List<Statistics> statistics(String taskId) {
        List<Statistics> resultList = new ArrayList<>();
        List<EconomicLossPDCalculation> list = economicLossPDRepository.getByTaskId(taskId);
        //获取评估任务关联的省市区县
        List<PCC> pccs = pccRepository.queryToponym(taskId);
        if(PlatformObjectUtils.isEmpty(pccs) || pccs.size() == 0){
            throw new RuntimeException("任务没有关联任何评估区域");
        }
        List<String> provinceList = pccs.stream().map(PCC::getPpName).distinct().collect(Collectors.toList());
        for (String province : provinceList) {
            List<String> cityList = pccs.stream().filter(pcc->province.equals(pcc.getPpName())).map(PCC::getCityName).distinct().collect(Collectors.toList());
            List<EconomicLossPDCalculation> pList = list.stream().filter(economicLossPDCalculation -> province.equals(economicLossPDCalculation.getProvinceName())).collect(Collectors.toList());
            if(PlatformObjectUtils.isNotEmpty(pList) && pList.size()>0){
                Map<String, List<EconomicLossPDCalculation>> collectMap = pList.stream().collect(Collectors.groupingBy(EconomicLossPDCalculation::getExtreme));
                for (String extreme : extremeList()) {
                    List<EconomicLossPDCalculation> casualtiesPECalculations = collectMap.get(extreme);
                    //存在多个市 需要展示省
                    if (cityList.size() > 1) {
                        BigDecimal proTotal = casualtiesPECalculations.stream()
                                .map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())) // 提取每个RiskAnalysisDeductDetail的Score字段
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        Statistics proStatistics = buildEntityData(province,proTotal,extreme);
                        List<Statistics> cityChildren = new ArrayList<>();
                        for (String city : cityList) {
                            List<String> countyList = pccs.stream().filter(pcc->city.equals(pcc.getCityName())).map(PCC::getName).distinct().collect(Collectors.toList());
                            BigDecimal cityTotal = casualtiesPECalculations.stream().filter(casualtiesPECalculation -> {
                                return city.equals(casualtiesPECalculation.getCityName());
                            }).map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())).
                                    reduce(BigDecimal.ZERO, BigDecimal::add);
                            Statistics cityStatistics = buildEntityData(city,cityTotal,extreme);
                            List<Statistics> countyChildren = new ArrayList<>();
                            for (String county : countyList) {
                                BigDecimal countyTotal = casualtiesPECalculations.stream().filter(casualtiesPECalculation -> {
                                    return county.equals(casualtiesPECalculation.getCountyName());
                                }).map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())).reduce(BigDecimal.ZERO, BigDecimal::add);
                                Statistics countyStatistics = buildEntityData(county,countyTotal,extreme);
                                countyChildren.add(countyStatistics);
                            }
                            cityStatistics.setChildren(countyChildren);
                            cityChildren.add(cityStatistics);
                        }
                        proStatistics.setChildren(cityChildren);
                        resultList.add(proStatistics);
                    }else {
                        List<String> countyList = pccs.stream().filter(pcc->cityList.get(0).equals(pcc.getCityName())).map(PCC::getName).distinct().collect(Collectors.toList());
                        if (countyList.size() > 1) {
                            BigDecimal cityTotal = casualtiesPECalculations.stream().filter(casualtiesPECalculation -> {
                                return cityList.get(0).equals(casualtiesPECalculation.getCityName());
                            }).map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())).
                                    reduce(BigDecimal.ZERO, BigDecimal::add);
                            Statistics cityStatistics = buildEntityData(cityList.get(0),cityTotal,extreme);
                            List<Statistics> countyChildren = new ArrayList<>();
                            for (String county : countyList) {
                                BigDecimal countyTotal = casualtiesPECalculations.stream().filter(casualtiesPECalculation -> {
                                    return county.equals(casualtiesPECalculation.getCountyName());
                                }).map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())).reduce(BigDecimal.ZERO, BigDecimal::add);
                                Statistics countyStatistics = buildEntityData(county,countyTotal,extreme);
                                countyChildren.add(countyStatistics);
                            }
                            cityStatistics.setChildren(countyChildren);
                            resultList.add(cityStatistics);
                        }else {
                            BigDecimal countyTotal = casualtiesPECalculations.stream().filter(casualtiesPECalculation -> {
                                return countyList.get(0).equals(casualtiesPECalculation.getCountyName());
                            }).map(economicLossPDCalculation -> new BigDecimal(economicLossPDCalculation.getCorrectionValue())).reduce(BigDecimal.ZERO, BigDecimal::add);
                            Statistics countyStatistics = buildEntityData(countyList.get(0),countyTotal,extreme);
                            resultList.add(countyStatistics);
                        }

                    }
                }
            }
        }
        return resultList;
    }

    private Statistics buildEntityData(String districtName, BigDecimal total, String extreme) {
        Statistics statistics = new Statistics();
        statistics.setId(UUIDGenerator.getUUID()).setDistrictName(districtName).setValue(total).setExtreme(extremeMap().get(extreme));
        return statistics;
    }

    private Map<String,String> extremeMap(){
        Map<String,String> map = new HashMap<>();
        map.put("pgcd2","轻微破坏");
        map.put("pgcd3","中等破坏");
        map.put("pgcd4","严重破坏");
        map.put("pgcd5","倒塌");
        return  map;
    }
    private List<String> extremeList(){
        return  Arrays.asList("pgcd2","pgcd3","pgcd4","pgcd5");
    }
}
